#    Copyright 2008, 2009, 2010, 2011, 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.


#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, cis, compatibleunit, geography, maintenance, oms, staker, symbology, unsorted, vegetationmanager
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql
from django.db.models import Max
import cPickle


#***********************************************************************************************
#For Objectid, -1 means that there is no Objectid specified
#For ObjectIndexWhenReverseSorted, -1 means to not return an object (-1,-1 means None is specified)
#***********************************************************************************************



def Reprocess():
    """Reprocess attempts to process all failed commands"""
    Commands=Command.objects.filter(CommandProcessedIndicator=False).order_by('id')
    for i in Commands:
        try:
            i.Process()
        except:
            i.CommandProcessFailedIndicator=True
            i.save()
            
CommandCommonFields=['Name', 'CommandUserName', 'CommandCreateDateTime']

CommandDictionary={
    'MoveStation': ['StartPoint', 'dx', 'dy'],

    'CreateStation': ['StartPoint'],

    'CreateSpan': ['StartPoint', 'EndPoint', 'JointTrenchIndicator', 
                  'TapIndicator', 'StakerStopTraceIndicator'],

    'UpdateStationComment': ['StartPoint', 'Description'],
  
    'UpdateStationTransformerUsageAnalysisComment': ['StartPoint', 'Description'],

    'UpdateSpanComment': ['StartPoint', 'EndPoint', 'Line', 'Description',
                          'TapIndicator', 'StakerStopTraceIndicator'],

    'DeleteStation': ['StartPoint'],

    'DeleteSpan': ['StartPoint', 'EndPoint', 'Line'],

    'CreateStationAssembly': ['StartPoint', 'AssemblyName', 'TagNumber', 'PutIntoServiceDate', 
                              'PrimaryIndicator', 'SecondaryIndicator', 'ServiceIndicator', 'OpenIndicator', 
                              'PoleStubIndicator', 'PoleLightIndicator', 'PoleMeterIndicator','MeterOnPoleIndicator', 
                              'OwnerName', 'ManufacturerName','MeterFormName', 
                              'StakerWorkOrderid','StakerWorkOrderIndexWhenReverseSorted',
                              'PhaseAIndicator', 'PhaseBIndicator', 'PhaseCIndicator', 'PhaseNeutralIndicator', 
                              'CircuitNumber', 'SerialNumber', 'MeterNumber', 'MeterDCSINumber',
                              'OldMapNumber', 'MapNumber' , 'PLACEHOLDER', 'CreateDate', 'MeterServiceTypeName',
                              'Rotation', 'IdleIndicator', 'PhysicalAddress', 'InstallStatus', 'StakerRecipeNumber', 'TransformerBankid', 'TransformerBankIndexWhenReverseSorted'],

    'EditAssembly': ['Assemblyid', 'AssemblyName', 'TagNumber', 'PutIntoServiceDate','OwnerName', 'ManufacturerName',
                     'PrimaryIndicator', 'SecondaryIndicator', 'PoleStubIndicator', 'PoleLightIndicator', 'PoleMeterIndicator', 
                     'MeterFormName', 'StakerWorkOrderIndexWhenReverseSorted', 'OpenIndicator', 'MeterOnPoleIndicator', 
                     'PhaseAIndicator', 'PhaseBIndicator', 'PhaseCIndicator', 'PhaseNeutralIndicator',
                     'CircuitNumber', 'SerialNumber', 'MeterNumber', 'MeterDCSINumber', 'OldMapNumber', 'MapNumber' ,'ServiceIndicator', 
                     'PLACEHOLDER', 'LastModifyDate', 'MeterServiceTypeName', 'Rotation', 'IdleIndicator', 'PhysicalAddress', 
                     'InstallStatus', 'StakerWorkOrderid', 'StakerStationOverrideid', 'StakerRecipeNumber', 'TransformerBankid', 'TransformerBankIndexWhenReverseSorted'],

    'EditAssemblyCircuit': ['Objectid','ObjectIndexWhenReverseSorted', 'CompatibleUnitid','TransformerCutOutIndicator', 'OpenIndicator', 
                            'PhaseAIndicator', 'PhaseBIndicator', 'PhaseCIndicator', 'PhaseNeutralIndicator', 'CircuitNumber',
                            'BypassIndicator', 'BypassAssemblyid', 'BypassAssemblyIndexWhenReverseSorted'],

    'UpdatePoleRightOfWayStatus': ['StartPoint', 'PoleRightOfWayStatusName'],

    'CreatePoleJointUse': ['StartPoint', 'PoleJointUseTypeName', 'CompanyName'],

    'CreatePoleTreatment': ['StartPoint', 'PoleTreatmentTypeName', 'CompanyName', 'PoleTreatmentDate'],

    'CreatePoleTreatmentFull': ['StartPoint', 'PoleTreatmentTypeName', 'CompanyName', 'PoleTreatmentDate',
                                'BrokenGuyIndicator', 'BrokenInsulatorIndicator', 
                                'VisualInspectionIndicator', 'VisualInspectionAndExcavationIndicator', 
                                'InternalTreatmentIndicator', 'InternalVoidTreatmentIndicator', 
                                'LightningArrestorBlownIndicator', 'NewPoleIndicator', 'PoleLeaningIndicator', 
                                'SplitTopIndicator', 'InternalDecayTreatmentIndicator', 
                                'WoodpeckerHolesIndicator', 'WireNeutralLowIndicator', 'WirePrimaryLowIndicator', 
                                'WireSecondaryLowIndicator', 'RotIndicator', 'GroundlineTreatmentIndicator', 
                                'RejectedIndicator', 'Description', 'RepairedGroundIndicator', 'BrokenCrossarmIndicator',
                                'GuyMarkerReplacedQuantity', 'GuyMarkerTotalQuantity', 'DataRecordOnlyIndicator'],


    'EditPoleTreatmentFull': ['PoleTreatmentid', 'PoleTreatmentTypeName', 'CompanyName', 'PoleTreatmentDate',
                              'BrokenGuyIndicator', 'BrokenInsulatorIndicator', 
                              'VisualInspectionIndicator', 'VisualInspectionAndExcavationIndicator', 
                              'InternalTreatmentIndicator', 'InternalVoidTreatmentIndicator', 
                              'LightningArrestorBlownIndicator', 'NewPoleIndicator', 'PoleLeaningIndicator', 
                              'SplitTopIndicator', 'InternalDecayTreatmentIndicator', 
                              'WoodpeckerHolesIndicator', 'WireNeutralLowIndicator', 'WirePrimaryLowIndicator', 
                              'WireSecondaryLowIndicator', 'RotIndicator', 'GroundlineTreatmentIndicator', 
                              'RejectedIndicator', 'Description', 'RepairedGroundIndicator', 'BrokenCrossarmIndicator',
                              'GuyMarkerReplacedQuantity', 'GuyMarkerTotalQuantity', 'DataRecordOnlyIndicator'],

    'CreateSpanAssembly': ['StartPoint', 'EndPoint', 'Line', 'AssemblyName', 'PhaseAIndicator', 'PhaseBIndicator', 
                           'PhaseCIndicator', 'PhaseNeutralIndicator', 'CircuitNumber', 'PrimaryIndicator', 
                           'SecondaryIndicator', 'ServiceIndicator', 'CreateDate', 'IdleIndicator', 'InstallStatus', 
                           'StakerWorkOrderid', 'StakerWorkOrderIndexWhenReverseSorted', 
                           'StakerRecipeNumber'],

    'DeleteStationAssembly': ['StartPoint', 'AssemblyName'],
  
    'DeleteSpanAssembly': ['StartPoint', 'EndPoint', 'Line', 'AssemblyName'],

    'CreateCompatibleUnit': ['CompatibleUnitName', 'Description', 'CompatibleUnitCategoryid', 'LaborHours', 
                             'KVA', 'KVAR', 'InputVoltageid', 'FirstOutputVoltageid', 'SecondOutputVoltageid', 
                             'MaximumContinousAmp', 'Wattage', 'Height', 'Class', 'StationIndicator', 
                             'SpanIndicator', 'ConductorIndicator', 'ConduitIndicator', 'SpanGuyIndicator', 
                             'CapacitorIndicator', 'CutOutIndicator', 'FeederIndicator', 'GroundIndicator', 
                             'LightIndicator', 'LightningArrestorIndicator', 'OpenPointIndicator', 'VaultIndicator', 
                             'MiscellaneousEquipmentIndicator', 'PoleIndicator', 'RecloserIndicator',
                             'RegulatorIndicator', 'MeterIndicator', 'SubstationIndicator', 'SwitchIndicator', 
                             'TransformerIndicator', 'StakerPoleIndicator', 'StakerTransformerIndicator',
                             'StakerMiscEquipmentIndicator', 'StakerGroundIndicator', 'StakerGuyGuyIndicator', 'StakerGuyMarkerIndicator',
                             'StakerGuyAnchorIndicator', 'StakerUnitIndicator', 'StakerSpanAssemblyIndicator'],

    'DeletePoleJointUse': ['PoleJointUseid'],

    'DeletePoleTreatment': ['PoleTreatmentid'],

    'DeleteAssembly': ['Assemblyid'],

    'CreateStakerWorkOrder': ['StakerWorkOrderName', 'Description', 'HazardsAssociatedWithJobIndicator', 
                              'WorkProcedureInvolvedIndicator', 'SpecialPrecautionsIndicator', 
                              'EnergySourceControlsIndicator', 'PPERequirementsIndicator', 'TailgateDiscussionIndicator',
                              'CheckWhereSepticTankIsIndicator', 'WorkPlanReferenceIndicator', 'NewConstructionIndicator', 
                              'SystemImprovementIndicator', 'ReplacementIndicator', 'Retire_No_ReplacementIndicator', 
                              'GeneralFundsIndicator', 'No_OfServicesOH', 'No_OfServicesUG',
                              'Wire', 'LoanNo', 'Substation', 'MapNo', 'LocationNextTo', 'CalhounCountyIndicator', 
                              'OrangeburgCountyIndicator', 'LexingtonCountyIndicator', 'RichlandCountyIndicator', 
                              'KershawCountyIndicator', 'SumterCountyIndicator', 'WorkOrderNumber',
                              'W_P', 'N_W_P', 'EngineerStaked', 'EngineerChecked', 'EngineerReleasedForConst', 
                              'Co_PermitNo', 'PUPS', 'NewR_WIndicator', 'R_WToBeCutIndicator', 'R_WCutDate', 
                              'ExistingR_WIndicator', 'CreateDate', 'StakerPhaseStartIndicator', 
                              'StakerPhaseStartDate', 'OutToConstructionStartIndicator', 'OutToConstructionStartDate',
                              'VerificationPhaseStartIndicator', 'VerificationPhaseStartDate',
                              'ArchivedIndicator', 'ArchivedDate', 'DeletedIndicator', 'DisplayMapOutlineIndicator', 
                              'MinimumX', 'MinimumY', 'MaximumX', 'MaximumY', 'AutomaticallyRecalculateExtentsIndicator', 
                              'StationListOverride', 'StationSortByDistanceIndicator', 'EstimateOnlyIndicator'],

    'EditStakerWorkOrder': ['StakerWorkOrderid', 'StakerWorkOrderName', 'Description', 'HazardsAssociatedWithJobIndicator', 
                            'WorkProcedureInvolvedIndicator', 'SpecialPrecautionsIndicator', 
                            'EnergySourceControlsIndicator', 'PPERequirementsIndicator', 'TailgateDiscussionIndicator',
                            'CheckWhereSepticTankIsIndicator', 'WorkPlanReferenceIndicator', 'NewConstructionIndicator', 
                            'SystemImprovementIndicator', 'ReplacementIndicator', 'Retire_No_ReplacementIndicator', 
                            'GeneralFundsIndicator', 'No_OfServicesOH', 'No_OfServicesUG', 'Wire', 'LoanNo', 'Substation', 
                            'MapNo', 'LocationNextTo', 'CalhounCountyIndicator', 'OrangeburgCountyIndicator',
                            'LexingtonCountyIndicator', 'RichlandCountyIndicator', 'KershawCountyIndicator', 
                            'SumterCountyIndicator', 'WorkOrderNumber', 'W_P', 'N_W_P', 'EngineerStaked', 
                            'EngineerChecked', 'EngineerReleasedForConst', 'Co_PermitNo', 'PUPS', 'NewR_WIndicator',
                            'R_WToBeCutIndicator', 'R_WCutDate', 'ExistingR_WIndicator', 'CreateDate',
                            'StakerPhaseStartIndicator', 'StakerPhaseStartDate', 'OutToConstructionStartIndicator', 
                            'OutToConstructionStartDate', 'VerificationPhaseStartIndicator',  'VerificationPhaseStartDate',
                            'ArchivedIndicator', 'ArchivedDate', 'DeletedIndicator', 'DisplayMapOutlineIndicator', 
                            'MinimumX', 'MinimumY', 'MaximumX', 'MaximumY', 'AutomaticallyRecalculateExtentsIndicator', 
                            'StationListOverride', 'StationSortByDistanceIndicator', 'ChangeUserNameIndicator', 
                            'EstimateOnlyIndicator'],  

    'DeleteStakerWorkOrder': ['StakerWorkOrderid'],

    'UndeleteStakerWorkOrder': ['StakerWorkOrderid'],

    'CreateProtectingAssembly': ['StartPoint', 'EndPoint', 'AssemblyName', 'IndexWhenSorted'],

    'DeleteProtectingAssembly': ['StartPoint', 'EndPoint', 'AssemblyName', 'IndexWhenSorted'],

    'CreateVegetationManagerJob': ['Description', 'VegetationManagerCrewid', 'WorkStartDate', 'WorkEndDate',
                                    'CreateDate', 'VegetationManagerJobStatusid', 'HoursWorkedQuantity', 'WidthInFeet',
                                    'ActiveIndicator', 'CreateCommand', 'SubstationName', 'CircuitName',
                                    'TrimRightOfWayIndicator'],


    'EditVegetationManagerJob': ['VegetationManagerJobid', 'VegetationManagerCrewid', 
                                 'Description', 'WorkStartDate', 'WorkEndDate', 
                                 'VegetationManagerJobStatusid', 
                                 'HoursWorkedQuantity', 'WidthInFeet', 'ActiveIndicator',
                                 'TrimRightOfWayIndicator', 'SubstationName', 'CircuitName'],

    'DeleteVegetationManagerJob': ['VegetationManagerJobid'],

    'CreateVegetationManagerJobStatus': ['VegetationManagerJobStatusName', 'Description'],

    'EditVegetationManagerJobStatus': ['VegetationManagerJobStatusid', 'VegetationManagerJobStatusName', 'Description'],

    'DeleteVegetationManagerJobStatus': ['VegetationManagerJobStatusid'],

    'CreateVegetationManagerJobSpan': ['VegetationManagerJobid', 'Line', 'Spanid', 'SymbologyJobYear'],

    'EditVegetationManagerJobSpan': ['VegetationManagerJobSpanid', 'Line', 'WidthInFeet', 'VegetationManagerJobid', 
                                     'VegetationManagerJobIndexWhenReverseSorted', 'WorkCompletedDate'],

    'DeleteVegetationManagerJobSpan': ['VegetationManagerJobSpanid'],




    'CreateTransformerBank': ['Description', 'TransformerBankTypeName', 'Stationid', 'StationIndexWhenReverseSorted' ],
    'DeleteTransformerBank': ['Objectid', 'ObjectIndexWhenReverseSorted'],




    'CreateVegetationManagerCrew': ['WorkerQuantity', 'Companyid', 'CompanyIndexWhenReverseSorted', 'WorkStartDate', 
                                    'WorkEndDate', 'ActiveIndicator', 'RadioNumber'],

    'EditVegetationManagerCrew': ['WorkerQuantity', 'VegetationManagerCrewid', 'Companyid', 
                                  'CompanyIndexWhenReverseSorted', 'WorkStartDate', 'WorkEndDate', 'ActiveIndicator', 
                                  'RadioNumber'],

    'DeleteVegetationManagerCrew': ['VegetationManagerCrewid'],

    'CreateCompany': ['ObjectName', 'Description', 'PoleTreatmentIndicator', 'PoleJointUseIndicator', 
                      'ManufacturerIndicator', 'VegetationManagementIndicator', 'ContractorIndicator', 'GroundRodTestIndicator'],

    'EditCompany': ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'PoleTreatmentIndicator', 
                    'PoleJointUseIndicator', 'ManufacturerIndicator', 'VegetationManagementIndicator', 
                    'ContractorIndicator', 'GroundRodTestIndicator'],

    'DeleteCompany': ['CompanyName'],

    'CreateCompatibleUnitPrice': ['CompatibleUnitName', 'CodedInstallPrice', 'Description',
                                  'CodedRemovePrice', 'Companyid', 'CompatibleUnitPriceContractid', 'CompatibleUnitPriceContractIndexWhenReverseSorted'],

    'EditCompatibleUnitPrice': ['Objectid', 'ObjectIndexWhenReverseSorted', 'Description',
                                'CodedInstallPrice', 'CodedRemovePrice', 'CompatibleUnitPriceContractid', 'CompatibleUnitPriceContractIndexWhenReverseSorted'],

    'DeleteCompatibleUnitPrice': ['Objectid'],


    'CreateCompatibleUnitPriceContract': ['ObjectName', 'Description', 'ActiveIndicator', 'StartDate', 'EndDate', 
                                          'CompanyName'],

    'EditCompatibleUnitPriceContract': ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'ActiveIndicator', 'StartDate', 'EndDate', 
                                          'CompanyName'],

    'DeleteCompatibleUnitPriceContract': ['Objectid'],

    'CreateBoardDistrict': ['ObjectName', 'Description', 'Polygon'],

    'EditBoardDistrict': ['ObjectName', 'Description', 'Polygon', 'Objectid', 'ObjectIndexWhenReverseSorted'],

    'DeleteBoardDistrict': ['Objectid'],

    'CreateLandmarkType' : ['ObjectName', 'Description', 'PointIndicator', 'LineIndicator', 'PolygonIndicator'],
    'EditLandmarkType' : ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'PointIndicator', 'LineIndicator', 'PolygonIndicator'],
    'DeleteLandmarkType' : ['Objectid'],

    'CreateLandmarkPoint' : ['ObjectName', 'Description', 'StartPoint', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'EditLandmarkPoint' : ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'StartPoint', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'DeleteLandmarkPoint' : ['Objectid'],

    'CreateLandmarkLine' : ['ObjectName', 'Description', 'Line', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'EditLandmarkLine' : ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'Line', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'DeleteLandmarkLine' : ['Objectid'],

    'CreateLandmarkPolygon' : ['ObjectName', 'Description', 'Polygon', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'EditLandmarkPolygon' : ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'Polygon', 'LandmarkTypeid', 'LandmarkTypeIndexWhenReverseSorted'],
    'DeleteLandmarkPolygon' : ['Objectid'],

    'CreateRoad': ['Line', 'ObjectName', 'InterstateIndicator', 'USHighwayIndicator', 'StateHighwayIndicator', 
                   'MainRoadIndicator', 'LeftFromAddress', 'LeftToAddress', 'RightFromAddress', 'RightToAddress'],
    'EditRoad': ['Line', 'ObjectName', 'InterstateIndicator', 'USHighwayIndicator', 'StateHighwayIndicator', 
                 'MainRoadIndicator', 'LeftFromAddress', 'LeftToAddress', 'RightFromAddress', 'RightToAddress',  
                 'Objectid', 'ObjectIndexWhenReverseSorted'],
    'DeleteRoad': ['Objectid'],

    'CreateCondition': ['PriorityImmediateIndicator', 'PriorityASAPIndicator', 'PriorityRoutineIndicator', 
                        'PriorityEverythingFixedMaintenanceOnlyIndicator', 'PriorityEverythingOkInspectionOnlyIndicator',
                        'PriorityVegetationNeedsAttentionIndicator', 'PriorityOutdoorLightingConversionIndicator', 
                        'NeedsRetirementIndicator', 
                        'ConditionDepartmentid', 'PersonReporting', 'DateTimeReported', 'ReceivedByOperationsIndicator', 'DateTimeReceivedByOperations',  
                        'StationIdentifier', 'TagNumber', 'StartPoint', 'Description', 
                        'OutdoorLightMapNumber', 'OutdoorLightMeterNumber', 'OutdoorLightMeterMapNumber', 
                        'OutdoorLightIdleIndicator', 'OutdoorLightCustomerOwnsPoleIndicator', 'OutdoorLightCustomerOwnsLightIndicator',
                        'OutdoorLightRateid', 'OutdoorLightProblemCodeid', 'OutdoorLightAdditionalBillingPoleCount',
                        'PoleConditionStatus', 'GuyAnchorConditionStatus', 'InsulatorConditionStatus', 'ConductorConditionStatus',
                        'RightOfWayConditionStatus', 'PadMountConditionStatus','VaultConditionStatus', 'RiserCableConditionStatus',
                        'WorkOrderNumber', 'WorkRemarks', 'WorkPerformedBy', 'HoursWorkedQuantity', 'WorkDate',
                        'WorkCompletedIndicator', 'WorkNotCompletedIndicator', 'WorkNotCompletedDescription',
                        'WorkForeman', 'WorkForemanSignoffIndicator', 'WorkForemanSignoffDateTime', 
                        'ReviewIndicator', 'ReviewAdditionalAttentionNeededIndicator', 'ReviewComments', 'ReviewUserName', 'ReviewDateTime',
                        'DeletedIndicator', 'ArchivedIndicator',
                        'OutdoorLightConsumerOwnedLightCount',
                        'OutdoorLightGISPhaseIndicator', 'OutdoorLightSendBackToBillingPhaseIndicator'],
    'EditCondition': ['Objectid', 'ObjectIndexWhenReverseSorted',
                      'PriorityImmediateIndicator', 'PriorityASAPIndicator', 'PriorityRoutineIndicator', 
                      'PriorityEverythingFixedMaintenanceOnlyIndicator', 'PriorityEverythingOkInspectionOnlyIndicator',
                      'PriorityVegetationNeedsAttentionIndicator', 'PriorityOutdoorLightingConversionIndicator',
                      'NeedsRetirementIndicator',
                      'ConditionDepartmentid', 'PersonReporting', 'DateTimeReported', 'ReceivedByOperationsIndicator', 'DateTimeReceivedByOperations',
                      'StationIdentifier', 'TagNumber', 'StartPoint', 'Description', 
                      'OutdoorLightMapNumber', 'OutdoorLightMeterNumber', 'OutdoorLightMeterMapNumber', 
                      'OutdoorLightIdleIndicator', 'OutdoorLightCustomerOwnsPoleIndicator', 'OutdoorLightCustomerOwnsLightIndicator',
                      'OutdoorLightRateid', 'OutdoorLightProblemCodeid', 'OutdoorLightAdditionalBillingPoleCount',
                      'PoleConditionStatus', 'GuyAnchorConditionStatus', 'InsulatorConditionStatus', 'ConductorConditionStatus',
                      'RightOfWayConditionStatus', 'PadMountConditionStatus','VaultConditionStatus', 'RiserCableConditionStatus',
                      'WorkOrderNumber', 'WorkRemarks', 'WorkPerformedBy','HoursWorkedQuantity', 'WorkDate', 
                      'WorkCompletedIndicator', 'WorkNotCompletedIndicator', 'WorkNotCompletedDescription',
                      'WorkForeman', 'WorkForemanSignoffIndicator', 'WorkForemanSignoffDateTime', 
                      'ReviewIndicator', 'ReviewAdditionalAttentionNeededIndicator', 'ReviewComments', 'ReviewUserName', 'ReviewDateTime',
                      'DeletedIndicator', 'ArchivedIndicator',
                      'OutdoorLightConsumerOwnedLightCount',
                      'OutdoorLightGISPhaseIndicator', 'OutdoorLightSendBackToBillingPhaseIndicator'],

    'CreateConditionMemberDescriptionHistory' : ['Conditionid', 'ConditionIndexWhenReverseSorted', 'Description'  ],
  
    'EditConditionMemberDescriptionHistory' : ['Objectid', 'ObjectIndexWhenReverseSorted', 'Conditionid', 'ConditionIndexWhenReverseSorted', 'Description'],

    #For CreateConditionAssignment, Object represents the Condition object that is being pointed to.
    'CreateConditionAssignment': ['ObjectName', 'Description', 'Objectid', 'ObjectIndexWhenReverseSorted'],

    'CreateSubstation': ['ObjectName', 'Description', 'Assemblyid', 'AssemblyIndexWhenReverseSorted', 'ActiveIndicator'], 

    'EditSubstation': ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'Assemblyid', 
                       'AssemblyIndexWhenReverseSorted', 'ActiveIndicator'],
    'DeleteSubstation': ['Objectid'],
    'CreateSubstationEquipment': ['SubstationEquipmentName', 'InventoryNumber', 'CatalogNumber', 
                                  'RatedTransmissionVoltage1id', 'RatedTransmissionVoltage1IndexWhenReverseSorted', 
                                  'RatedTransmissionVoltage2id', 'RatedTransmissionVoltage2IndexWhenReverseSorted',
                                  'RatedDistributionVoltage1id', 'RatedDistributionVoltage1IndexWhenReverseSorted', 
                                  'RatedDistributionVoltage2id', 'RatedDistributionVoltage2IndexWhenReverseSorted',
                                  'OperatorControlVoltageid', 'OperatorControlVoltageIndexWhenReverseSorted',
                                  'CurrentTransmissionVoltageid', 'CurrentTransmissionVoltageIndexWhenReverseSorted',
                                  'CurrentDistributionVoltageid', 'CurrentDistributionVoltageIndexWhenReverseSorted',
                                  'KVARating', 'MVARating', 'FanQuantity', 'SubstationEquipmentModelTypeid',
                                  'SubstationEquipmentModelTypeIndexWhenReverseSorted',
                                  'Manufacturerid', 'ManufacturerIndexWhenReverseSorted',
                                  'DateOfManufacture', 'Impedance', 'OilCapacityGallon', 'WeightPound',
                                  'BatteryChargerManufacturerid', 'BatteryChargerManufacturerIndexWhenReverseSorted',
                                  'BatteryChargerDateOfManufacture', 
                                  'BatteryChargerInputVoltageid', 'BatteryChargerInputVoltageIndexWhenReverseSorted',
                                  'BatteryChargerOutputVoltageid', 'BatteryChargerOutputVoltageIndexWhenReverseSorted',
                                  'BatteryChargerACAmps', 'BatteryChargerDCAmps', 'BatteryChargerNumberOfCells',
                                  'BatteryChargerTypeOfCells', 'BatteryBankBatteryVoltage', 'BatteryBankBatteryAmpHours',
                                  'BatteryBankBatteryReserveCapacity', 'BatteryBankBatteryModelNumber', 
                                  'SubstationEquipmentOverCurrentRelayTypeid', 'SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted', 
                                  'SubstationEquipmentDifferentialRelayTypeid', 'SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted',
                                  'SubstationEquipmentRegulatorControllerTypeid', 'SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted',
                                  'RegulatorControllerSerialNumber',
                                  'RecloserControllerTypeid', 'RecloserControllerTypeIndexWhenReverseSorted', 
                                  'SerialNumber', 'Description', 'Assemblyid', 'AssemblyIndexWhenReverseSorted', 
                                  'ActiveIndicator', 'SubstationEquipmentTemplateid', 'SubstationEquipmentTemplateIndexWhenReverseSorted'],
    'EditSubstationEquipment':['Objectid', 'ObjectIndexWhenReverseSorted', 'SubstationEquipmentName', 'InventoryNumber', 'CatalogNumber', 
                               'RatedTransmissionVoltage1id', 'RatedTransmissionVoltage1IndexWhenReverseSorted', 
                               'RatedTransmissionVoltage2id', 'RatedTransmissionVoltage2IndexWhenReverseSorted',
                               'RatedDistributionVoltage1id', 'RatedDistributionVoltage1IndexWhenReverseSorted', 
                               'RatedDistributionVoltage2id', 'RatedDistributionVoltage2IndexWhenReverseSorted',
                               'OperatorControlVoltageid', 'OperatorControlVoltageIndexWhenReverseSorted',
                               'CurrentTransmissionVoltageid', 'CurrentTransmissionVoltageIndexWhenReverseSorted',
                               'CurrentDistributionVoltageid', 'CurrentDistributionVoltageIndexWhenReverseSorted',
                               'KVARating', 'MVARating', 'FanQuantity', 'SubstationEquipmentModelTypeid',
                               'SubstationEquipmentModelTypeIndexWhenReverseSorted',
                               'Manufacturerid', 'ManufacturerIndexWhenReverseSorted',
                               'DateOfManufacture', 'Impedance', 'OilCapacityGallon', 'WeightPound',
                               'BatteryChargerManufacturerid', 'BatteryChargerManufacturerIndexWhenReverseSorted',
                               'BatteryChargerDateOfManufacture', 
                               'BatteryChargerInputVoltageid', 'BatteryChargerInputVoltageIndexWhenReverseSorted',
                               'BatteryChargerOutputVoltageid', 'BatteryChargerOutputVoltageIndexWhenReverseSorted',
                               'BatteryChargerACAmps', 'BatteryChargerDCAmps', 'BatteryChargerNumberOfCells',
                               'BatteryChargerTypeOfCells', 'BatteryBankBatteryVoltage', 'BatteryBankBatteryAmpHours',
                               'BatteryBankBatteryReserveCapacity', 'BatteryBankBatteryModelNumber', 
                               'SubstationEquipmentOverCurrentRelayTypeid', 'SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted', 
                               'SubstationEquipmentDifferentialRelayTypeid', 'SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted',
                               'SubstationEquipmentRegulatorControllerTypeid', 'SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted',
                               'RegulatorControllerSerialNumber',
                               'RecloserControllerTypeid', 'RecloserControllerTypeIndexWhenReverseSorted', 
                               'SerialNumber', 'Description', 'Assemblyid', 'AssemblyIndexWhenReverseSorted', 
                               'ActiveIndicator',
                               'SubstationEquipmentTemplateid', 'SubstationEquipmentTemplateIndexWhenReverseSorted'],
    'DeleteSubstationEquipment':['Objectid'],
    'CreateSubstationEquipmentInspection': ['CreateDateTime', 'CreateUserName', 'Description', 
                                            'BatteryTestid', 'BatteryTestIndexWhenReverseSorted',
                                            'BatteryCharge', 'BatteryVisualid', 'BatteryVisualIndexWhenReverseSorted',
                                            'BatteryVoltageTest', 'BatteryVoltageNormal', 'Groundid', 'GroundIndexWhenReverseSorted',
                                            'Visualid', 'VisualIndexWhenReverseSorted', 
                                            'MeterKWH', 'MeterKW', 'FanWorkingVisualid', 'FanWorkingVisualIndexWhenReverseSorted',
                                            'MeterVisualid', 'MeterVisualIndexWhenReverseSorted',  
                                            'RecloserAmperageA', 'RecloserAmperageB', 'RecloserAmperageC',
                                            'RecloserAmperageGround', 'RecloserMaxDemandA', 'RecloserMaxDemandB', 'RecloserMaxDemandC',
                                            'RecloserMaxDemandGround', 'RecloserOperationSummaryA', 'RecloserOperationSummaryB', 
                                            'RecloserOperationSummaryC', 'RecloserTargetA', 'RecloserTargetB', 'RecloserTargetC',
                                            'RecloserTargetGround', 'RegulatorDragHandPositionMinimum', 
                                            'RegulatorDragHandPositionCurrent', 'RegulatorDragHandPositionMaximum', 'RegulatorVoltHigh',
                                            'RegulatorVoltLow', 'RegulatorVoltCurrent', 'RegulatorMaxAmp', 
                                            'SurgeProtectorVisualid', 'SurgeProtectorVisualIndexWhenReverseSorted', 
                                            'TransformerOilLeakid', 'TransformerOilLeakIndexWhenReverseSorted', 
                                            'TransformerOilLevelid', 'TransformerOilLevelIndexWhenReverseSorted', 
                                            'TransformerOilTemperatureCurrent', 'TransformerOilTemperatureMaximum',
                                            'TransformerNitrogenPressure',  
                                            'TransformerOilVisualid', 'TransformerOilVisualIndexWhenReverseSorted', 
                                            'TransformerWindingTemperatureCurrent', 'TransformerWindingTemperatureMaximum',
                                            'SubstationEquipmentid', 'SubstationEquipmentIndexWhenReverseSorted',
                                            'MechanismChargeid', 'MechanismChargeIndexWhenReverseSorted', 'OperationCounter',
                                            'DemandAmpA', 'DemandAmpB', 'DemandAmpC', 'OverCurrentTrip',
                                            'BreakerCounter'],
    'EditSubstationEquipmentInspection': ['Objectid', 'ObjectIndexWhenReverseSorted', 'LastModifyDateTime', 'LastModifyUserName', 'Description', 
                                          'BatteryTestid', 'BatteryTestIndexWhenReverseSorted',
                                          'BatteryCharge', 'BatteryVisualid', 'BatteryVisualIndexWhenReverseSorted',
                                          'BatteryVoltageTest', 'BatteryVoltageNormal', 'Groundid', 'GroundIndexWhenReverseSorted', 
                                          'Visualid', 'VisualIndexWhenReverseSorted', 
                                          'MeterKWH', 'MeterKW', 'FanWorkingVisualid', 'FanWorkingVisualIndexWhenReverseSorted',
                                          'MeterVisualid', 'MeterVisualIndexWhenReverseSorted',  
                                          'RecloserAmperageA', 'RecloserAmperageB', 'RecloserAmperageC',
                                          'RecloserAmperageGround', 'RecloserMaxDemandA', 'RecloserMaxDemandB', 'RecloserMaxDemandC',
                                          'RecloserMaxDemandGround', 'RecloserOperationSummaryA', 'RecloserOperationSummaryB', 
                                          'RecloserOperationSummaryC', 'RecloserTargetA', 'RecloserTargetB', 'RecloserTargetC',
                                          'RecloserTargetGround', 'RegulatorDragHandPositionMinimum', 'RegulatorDragHandPositionCurrent',
                                          'RegulatorDragHandPositionMaximum', 'RegulatorVoltHigh',
                                          'RegulatorVoltLow', 'RegulatorVoltCurrent', 'RegulatorMaxAmp', 
                                          'SurgeProtectorVisualid', 'SurgeProtectorVisualIndexWhenReverseSorted', 
                                          'TransformerOilLeakid', 'TransformerOilLeakIndexWhenReverseSorted', 
                                          'TransformerOilLevelid', 'TransformerOilLevelIndexWhenReverseSorted', 
                                          'TransformerOilTemperatureCurrent', 'TransformerOilTemperatureMaximum', 'TransformerNitrogenPressure',  
                                          'TransformerOilVisualid', 'TransformerOilVisualIndexWhenReverseSorted', 
                                          'TransformerWindingTemperatureCurrent', 'TransformerWindingTemperatureMaximum',
                                          'SubstationEquipmentid', 'SubstationEquipmentIndexWhenReverseSorted',
                                          'MechanismChargeid', 'MechanismChargeIndexWhenReverseSorted', 'OperationCounter',  'DemandAmpA', 
                                          'DemandAmpB', 'DemandAmpC', 'OverCurrentTrip',
                                          'BreakerCounter'],
    'DeleteSubstationEquipmentInspection': ['Objectid'],
    'CreateSubstationEquipmentTemplate': ['ObjectName', 'DescriptionOrder', 'BatteryTestOrder', 'BatteryVoltageNormalOrder', 
                                          'BatteryVoltageTestOrder', 'BatteryChargeOrder',
                                          'BatteryVisualOrder', 'GroundOrder', 'VisualOrder', 
                                          'MeterKWHOrder', 'MeterKWOrder', 'RecloserAmperageAOrder', 
                                          'RecloserAmperageBOrder', 'RecloserAmperageCOrder', 'RecloserAmperageGroundOrder', 
                                          'RecloserMaxDemandAOrder', 'RecloserMaxDemandBOrder', 'RecloserMaxDemandCOrder', 
                                          'RecloserMaxDemandGroundOrder', 'RecloserOperationCounterOrder', 'RecloserOperationSummaryAOrder',
                                          'RecloserOperationSummaryBOrder', 'RecloserOperationSummaryCOrder', 'RecloserTargetAOrder', 
                                          'RecloserTargetBOrder', 'RecloserTargetCOrder', 'RecloserTargetGroundOrder', 
                                          'RegulatorDragHandPositionMinimumOrder', 
                                          'RegulatorDragHandPositionMaximumOrder', 'RegulatorDragHandPositionCurrentOrder',
                                          'RegulatorVoltCurrentOrder', 'RegulatorVoltLowOrder', 'RegulatorVoltHighOrder',
                                          'RegulatorMaxAmpOrder', 'SurgeProtectorVisualOrder', 
                                          'TransformerOilLeakOrder', 'TransformerOilLevelOrder', 'TransformerOilTemperatureCurrentOrder',
                                          'TransformerOilTemperatureMaximumOrder', 'TransformerWindingTemperatureCurrentOrder', 
                                          'TransformerNitrogenPressureOrder', 'TransformerOilVisualOrder', 'TransformerWindingTemperatureMaximumOrder',
                                          'ActiveIndicator', 'MechanismChargeOrder', 'OperationCounterOrder',
                                          'FanWorkingVisualOrder', 'DemandAmpAOrder', 'DemandAmpBOrder', 'DemandAmpCOrder', 'OverCurrentTripOrder',
                                          'BreakerCounterOrder'],
    'EditSubstationEquipmentTemplate': ['Objectid', 'ObjectName', 'ObjectIndexWhenReverseSorted', 
                                        'DescriptionOrder', 'BatteryTestOrder', 'BatteryVoltageNormalOrder', 
                                        'BatteryVoltageTestOrder', 'BatteryChargeOrder',
                                        'BatteryVisualOrder', 'GroundOrder', 'VisualOrder', 
                                        'MeterKWHOrder', 'MeterKWOrder', 'RecloserAmperageAOrder', 
                                        'RecloserAmperageBOrder', 'RecloserAmperageCOrder', 'RecloserAmperageGroundOrder', 
                                        'RecloserMaxDemandAOrder', 'RecloserMaxDemandBOrder', 'RecloserMaxDemandCOrder', 
                                        'RecloserMaxDemandGroundOrder', 'RecloserOperationCounterOrder', 'RecloserOperationSummaryAOrder',
                                        'RecloserOperationSummaryBOrder', 'RecloserOperationSummaryCOrder', 'RecloserTargetAOrder', 
                                        'RecloserTargetBOrder', 'RecloserTargetCOrder', 'RecloserTargetGroundOrder', 
                                        'RegulatorDragHandPositionMinimumOrder', 
                                        'RegulatorDragHandPositionMaximumOrder', 'RegulatorDragHandPositionCurrentOrder',
                                        'RegulatorVoltCurrentOrder', 'RegulatorVoltLowOrder', 'RegulatorVoltHighOrder',
                                        'RegulatorMaxAmpOrder', 'SurgeProtectorVisualOrder', 
                                        'TransformerOilLeakOrder', 'TransformerOilLevelOrder', 'TransformerOilTemperatureCurrentOrder',
                                        'TransformerOilTemperatureMaximumOrder', 'TransformerWindingTemperatureCurrentOrder', 
                                        'TransformerNitrogenPressureOrder', 'TransformerOilVisualOrder', 'TransformerWindingTemperatureMaximumOrder',
                                        'ActiveIndicator', 'MechanismChargeOrder', 'OperationCounterOrder',
                                        'FanWorkingVisualOrder',  'DemandAmpAOrder', 'DemandAmpBOrder', 'DemandAmpCOrder', 'OverCurrentTripOrder',
                                        'BreakerCounterOrder'],
    'DeleteSubstationEquipmentTemplate': ['Objectid'],
    'CreateSubstationInspection': ['Substationid', 'SubstationIndexWhenReverseSorted', 'Description', 'CreateDateTime', 'CreateUserName', 
                                   'DynasphereVisualid', 'DynasphereVisualIndexWhenReverseSorted', 
                                   'BrokenPorcelainid', 'BrokenPorcelainIndexWhenReverseSorted',
                                   'CircuitIdentifierid', 'CircuitIdentifierIndexWhenReverseSorted', 
                                   'DynasphereOperationIndicator',
                                   'SurgeProtectorVisualid', 'SurgeProtectorVisualIndexWhenReverseSorted', 'Debrisid', 'DebrisIndexWhenReverseSorted',
                                   'FenceGroundLevelid', 'FenceGroundLevelIndexWhenReverseSorted', 
                                   'FenceOverallConditionid', 'FenceOverallConditionIndexWhenReverseSorted', 
                                   'FenceSecurityWireid', 'FenceSecurityWireIndexWhenReverseSorted',
                                   'FenceWarningSignid', 'FenceWarningSignIndexWhenReverseSorted',  
                                   'GateGroundid', 'GateGroundIndexWhenReverseSorted', 'GateLockid', 'GateLockIndexWhenReverseSorted',
                                   'GateWarningSignid', 'GateWarningSignIndexWhenReverseSorted', 
                                   'MaterialStoreid', 'MaterialStoreIndexWhenReverseSorted', 
                                   'SpillPreventionPlanid', 'SpillPreventionPlanIndexWhenReverseSorted', 'AMRVisualid', 'AMRVisualIndexWhenReverseSorted', 
                                   'Vegetationid', 'VegetationIndexWhenReverseSorted'],
    'EditSubstationInspection':  [ 'Objectid', 'ObjectIndexWhenReverseSorted', 'Substationid', 'SubstationIndexWhenReverseSorted', 'Description', 
                                   'LastModifyDateTime', 'LastModifyUserName',  
                                   'DynasphereVisualid', 'DynasphereVisualIndexWhenReverseSorted', 
                                   'BrokenPorcelainid', 'BrokenPorcelainIndexWhenReverseSorted',
                                   'CircuitIdentifierid', 'CircuitIdentifierIndexWhenReverseSorted', 
                                   'DynasphereOperationIndicator',
                                   'SurgeProtectorVisualid', 'SurgeProtectorVisualIndexWhenReverseSorted', 'Debrisid', 'DebrisIndexWhenReverseSorted',
                                   'FenceGroundLevelid', 'FenceGroundLevelIndexWhenReverseSorted', 
                                   'FenceOverallConditionid', 'FenceOverallConditionIndexWhenReverseSorted', 
                                   'FenceSecurityWireid', 'FenceSecurityWireIndexWhenReverseSorted',
                                   'FenceWarningSignid', 'FenceWarningSignIndexWhenReverseSorted',  
                                   'GateGroundid', 'GateGroundIndexWhenReverseSorted', 'GateLockid', 'GateLockIndexWhenReverseSorted',
                                   'GateWarningSignid', 'GateWarningSignIndexWhenReverseSorted', 
                                   'MaterialStoreid', 'MaterialStoreIndexWhenReverseSorted', 
                                   'SpillPreventionPlanid', 'SpillPreventionPlanIndexWhenReverseSorted', 'AMRVisualid', 'AMRVisualIndexWhenReverseSorted', 
                                   'Vegetationid', 'VegetationIndexWhenReverseSorted'],
    'DeleteSubstationInspection': ['Objectid'],
    'CreateSubstationInspectionChoice': ['ObjectName', 'Description', 'ActiveIndicator'],
    'EditSubstationInspectionChoice': ['Objectid', 'ObjectName', 'ObjectIndexWhenReverseSorted', 'Description', 'ActiveIndicator'],
    'CreateSubstationEquipmentModelType': ['ObjectName', 'Description', 'Manufacturerid', 'ManufacturerIndexWhenReverseSorted',
                                          'TransformerIndicator', 'RegulatorIndicator', 'RegulatorControllerIndicator',
                                          'TransmissionOverCurrentRelayIndicator', 'RecloserIndicator', 'RecloserControllerIndicator',
                                          'CircuitSwitcherIndicator', 'BatteryBankIndicator'],
    'EditSubstationEquipmentModelType': ['Objectid', 'ObjectName', 'ObjectIndexWhenReverseSorted', 'Description', 'Manufacturerid', 
                                         'ManufacturerIndexWhenReverseSorted', 'TransformerIndicator', 'RegulatorIndicator', 
                                         'RegulatorControllerIndicator', 'TransmissionOverCurrentRelayIndicator', 'RecloserIndicator', 
                                         'RecloserControllerIndicator', 'CircuitSwitcherIndicator', 'BatteryBankIndicator'],
    'CreateSubstationEquipmentSetting': ['ObjectName', 'Description'], 
    'EditSubstationEquipmentSetting': ['Objectid', 'ObjectIndexWhenReverseSorted', 'Description', 'ObjectName'],
    'DeleteSubstationEquipmentSetting': ['Objectid', 'ObjectIndexWhenReverseSorted'],
    'CreateSubstationEquipmentSettingAssignment': ['SubstationEquipmentid', 'SubstationEquipmentIndexWhenReverseSorted', 
                                                   'SubstationEquipmentSettingid', 'SubstationEquipmentSettingIndexWhenReverseSorted',
                                                   'DateTime'],
    'CreateSubstationEquipmentSubstationAssignment': ['Substationid', 'SubstationIndexWhenReverseSorted', 'SubstationEquipmentid', 
                                                      'SubstationEquipmentIndexWhenReverseSorted', 'Description', 'DateTime'], 
    'CreateSubstationEquipmentTest': ['SubstationEquipmentid', 'SubstationEquipmentIndexWhenReverseSorted', 'PassIndicator', 
                                      'Description', 'DateTime'], 
    'EditSubstationEquipmentTest': ['Objectid', 'ObjectIndexWhenReverseSorted', 'SubstationEquipmentid', 
                                    'SubstationEquipmentIndexWhenReverseSorted', 'PassIndicator', 'Description', 'DateTime'],
    'DeleteSubstationEquipmentTest': ['Objectid'],
    'CreateSubstationEquipmentCircuitAssignment': ['SubstationCircuitid', 'SubstationCircuitIndexWhenReverseSorted', 'SubstationEquipmentid', 
                                                      'SubstationEquipmentIndexWhenReverseSorted', 'Description', 'DateTime'], 
    'CreateSubstationCircuit': ['ObjectName', 'CircuitNumber', 'Substationid', 'SubstationIndexWhenReverseSorted', 
                                'AMRCircuitName', 'AMRSubstationIdentifier', 'AMRBusIdentifier', 'AMRFeederIdentifier',
                                'Description'], 
    'EditSubstationCircuit': ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'CircuitNumber', 'Substationid', 
                              'SubstationIndexWhenReverseSorted', 
                              'AMRCircuitName', 'AMRSubstationIdentifier', 'AMRBusIdentifier', 'AMRFeederIdentifier',
                              'Description' ],
    'CreateVoltage': ['ObjectName', 'Description', 'Value', 'TransmissionIndicator', 'PrimaryIndicator', 'SecondaryIndicator',
                      'ServiceIndicator'], 
    'EditVoltage': ['Objectid', 'ObjectIndexWhenReverseSorted', 'ObjectName', 'Description', 'Value', 'TransmissionIndicator', 
                    'PrimaryIndicator', 'SecondaryIndicator', 'ServiceIndicator'],
    'CreateWarehouseMeterInventoryCheckIn': ['MeterNumber', 'MeterDCSINumber', 'CheckInDateTime', 
                                             'WarehouseMeterInspectionChoiceid', 'WarehouseMeterInspectionChoiceIndexWhenReverseSorted', 
                                             'InspectionDateTime', 'CheckOutDateTime', 'Description',
                                             'JunkIndicator', 'JunkDateTime', 'Location'],
    'EditWarehouseMeterInventoryCheckIn': ['Objectid', 'ObjectIndexWhenReverseSorted', 'MeterNumber', 'MeterDCSINumber', 'CheckInDateTime', 
                                           'WarehouseMeterInspectionChoiceid', 'WarehouseMeterInspectionChoiceIndexWhenReverseSorted', 
                                           'InspectionDateTime', 'CheckOutDateTime', 'Description', 'JunkIndicator', 'JunkDateTime',
                                           'Location'],
    'CreateWarehouseMeterInspectionChoice': ['ObjectName', 'Description', 'ActiveIndicator'],
    'EditWarehouseMeterInspectionChoice': ['Objectid', 'ObjectName', 'ObjectIndexWhenReverseSorted', 'Description', 'ActiveIndicator'],
    'CreateGroundRodTest': ['StartPoint', 'GroundRodNumber', 'ResistanceReading', 'CompanyName', 'WorkOrderNumber', 'Description', 
                            'SetupIndicator', 'InspectionPersonName', 'SubstationName', 'CreateDateTime', 'GroundRodTestDate',
                            'LastModifyDateTime', 'CreateUserName', 'LastModifyUserName'],

    'EditGroundRodTest': ['Objectid', 'GroundRodNumber', 'ResistanceReading', 'CompanyName', 'WorkOrderNumber', 'Description',
                          'SetupIndicator', 'InspectionPersonName', 'SubstationName', 'CreateDateTime', 'GroundRodTestDate',
                          'LastModifyDateTime', 'CreateUserName', 'LastModifyUserName'],
    'DeleteGroundRodTest': ['GroundRodTestid'],}





def GetObjectFromidandReverseSortedIndex(ObjectString, Object, Dict):
    if(Dict[ObjectString + 'id'] and Dict[ObjectString + 'id'] <> -1):
        ReturnObject=Object.objects.filter(id=Dict[ObjectString + 'id'])[0]
    elif(Dict[ObjectString + 'IndexWhenReverseSorted'] <> -1):
        ReturnObject=Object.objects.all().order_by('-id')[Dict[ObjectString + 'IndexWhenReverseSorted']]
    else:
        ReturnObject=None
    return ReturnObject

def FindRecentCommands(station):
    commands=Command.objects.filter(StartPoint__distance_lte=(station.Point,25 * djangoproject.settings.COOPGISDistanceMultiplier))
    date = datetime.date(2008, 11, 11)
    for i in commands:
        if(i.CreateDate) and (i.CreateDate > date):
            print str(i.Name) + '   ' + str(i.CreateDate) + '   ' + str(i.CommandUserName)
        
HardCodedFields=('Name', 'CommandUserName', 'CommandCreateDateTime', 'CommandUpdateNumber', 
                 'StartPoint', 'EndPoint', 'Polygon', 'Line', 'AssemblyName', 'TagNumber')

class Command(models.Model):
    """Command is a list of commands that are stored in a table.  Export and Import functionality is performed through a pickled list of dictionaries"""
    Name=models.TextField(db_column='name')
    AssemblyName=models.TextField(db_column='assemblyname', null=True, blank=True)
    TagNumber=models.TextField(db_column='tagnumber', null=True, blank=True)
    CommandProcessedIndicator=models.NullBooleanField(db_column='commandprocessedindicator', null=True, blank=True)
    Dictionary=models.TextField(db_column='dictionary', null=True, blank=True)
    StartPoint=models.PointField(db_column='startpoint', srid=djangoproject.settings.COOPGISSRID, null=True, blank=True)
    EndPoint=models.PointField(db_column='endpoint', srid=djangoproject.settings.COOPGISSRID, null=True, blank=True)
    Polygon=models.PolygonField(db_column='polygon', srid=djangoproject.settings.COOPGISSRID, null=True, blank=True)
    Line=models.LineStringField(db_column='line', srid=djangoproject.settings.COOPGISSRID, null=True, blank=True)
    CommandResidesOnServerIndicator=models.NullBooleanField(db_column='commandresidesonserverindicator', null=True, blank=True)
    CommandProcessedDateTime=models.DateTimeField(db_column='commandprocesseddatetime', null=True, blank=True)
    CommandUserName=models.TextField(db_column='commandusername', null=True, blank=True)
    CommandCreateDateTime=models.DateTimeField(db_column='commandcreatedatetime', null=True, blank=True)
    CommandProcessFailedIndicator=models.NullBooleanField(db_column='commandprocessfailedindicator', null=True, blank=True) #Attempt to Process a Command Failed
    CommandUpdateNumber=models.TextField(db_column='commandupdatenumber', null=True, blank=True) #Update Number that a Command was associated with (if any)
    CommandVerifiedIndicator=models.NullBooleanField(db_column='commandverifiedindicator', null=True, blank=True) #Represents whether an uploaded command has been confirmed
    objects=models.GeoManager()
    ImportFromFileName='/opt/coopgis/command/Import.pickle'
    ExportToFileName='/opt/coopgis/command/Export.pickle'
    class Meta:
        db_table=u'coopgiscommand'
        app_label='djangoproject'
    #****************************START COMMAND PROCESS SECTION******************************
    def Process(self, RebuildSymbologyIndicator=True): 
        """RebuildSymbologyIndicator allows creation of station assemblies ONLY without rebuilding the symbology"""
        ReturnObject=None #Different objects are returned depending on the command being processed
        Dict=self.GetDictionary()
        if(not self.CommandVerifiedIndicator and djangoproject.settings.COOPGISServerIndicator):
            return False 
        if(self.CommandProcessedIndicator):
            return False 
        if(self.Name=='MoveStation'):
	    station=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]  
            station.Move(Dict['dx'], Dict['dy']) #Station.Move rebuilds symbology
            ReturnObject=station
	elif(self.Name=='CreateStation'):
	    station=geography.Station().GetOrCreateClosestStation(self.StartPoint, CreateCommand=self) #Station().GetOrCreateClosestStation rebuilds symbology
            ReturnObject=station
        elif(self.Name=='CreateSpan'):
	    span=geography.Span()
	    StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            EndStation=geography.Station().GetOrCreateClosestStation(self.EndPoint)
            if(Dict.has_key('TapIndicator')):
                TapIndicator=Dict['TapIndicator']
            else:
                TapIndicator=False
            if(Dict.has_key('StakerStopTraceIndicator')):
                StakerStopTraceIndicator=Dict['StakerStopTraceIndicator']
            else:
                StakerStopTraceIndicator=False
	    span=span.GetOrCreate(StartStation, EndStation, JointTrenchIndicator=Dict['JointTrenchIndicator'], 
                                  CreateCommand=self, TapIndicator=TapIndicator, 
                                  StakerStopTraceIndicator=StakerStopTraceIndicator) #Span.GetOrCreate rebuilds symbology
            ReturnObject=span
	elif(self.Name=='UpdateStationComment'):
            StartStation=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            StartStation.Description=Dict['Description']
            StartStation.save() #No symbology dependent on Description currently, so do not rebuild
            ReturnObject=StartStation
	elif(self.Name=='UpdateStationTransformerUsageAnalysisComment'):
            StartStation=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            StartStation.TransformerUsageAnalysisComment=Dict['Description']
            StartStation.save() #No symbology dependent on TransformerUsageAnalysisComment currently, so do not rebuild
            ReturnObject=StartStation
	elif(self.Name=='UpdateSpanComment'):
            StartStation=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            EndStation=geography.Station.objects.filter(Point__distance_lte=(self.EndPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            MatchingSpan=geography.Span().GetAllMatching(StartStation, EndStation)[0]
            MatchingSpan.Description=Dict['Description']
            MatchingSpan.TapIndicator=Dict['TapIndicator']
            MatchingSpan.StakerStopTraceIndicator=Dict['StakerStopTraceIndicator']
            MatchingSpan.save() #No symbology dependent on Description currently, so do not rebuild
            ReturnObject=MatchingSpan
	elif(self.Name=='DeleteStation'):
	    StartStation=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]   
	    if(StartStation.OKToDelete()):
                compatibleunit.PoleTreatment.objects.filter(Pole__Station=StartStation).delete()
	        StartStation.delete()
                ReturnObject=True
	    else:
                ReturnObject=False
	elif(self.Name=='DeleteSpan'):
            StartStation=geography.Station.objects.filter(Point__distance_lte=(self.StartPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            EndStation=geography.Station.objects.filter(Point__distance_lte=(self.EndPoint, .5 * djangoproject.settings.COOPGISDistanceMultiplier))[0]
            SpanToDelete=geography.Span().GetAllMatching(StartStation, EndStation)[0]
            if(SpanToDelete.OKToDelete()):
                ProtectingAssemblies=compatibleunit.ProtectingAssembly.objects.filter(Span=SpanToDelete)
                for i in ProtectingAssemblies:   
                    i.delete()
                SpanToDelete.delete()
                StartStation.RebuildSymbology()
                ReturnObject=True
            else:
                ReturnObject=False
        elif(self.Name=='CreateStationAssembly'):
            meterServiceType=COOPGIS_Misc.GetOneOrNone(compatibleunit.MeterServiceType.objects.filter(Name__exact=Dict['MeterServiceTypeName']))
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            owner=COOPGIS_Misc.GetOneOrNone(compatibleunit.AssemblyOwner.objects.filter(Name=Dict['OwnerName']))
            manufacturer=COOPGIS_Misc.GetOneOrNone(compatibleunit.Company.objects.filter(Name=Dict['ManufacturerName']))
            meterForm=COOPGIS_Misc.GetOneOrNone(compatibleunit.MeterForm.objects.filter(Name=Dict['MeterFormName']))
            installStatus=COOPGIS_Misc.GetOneOrNone(staker.InstallStatus.objects.filter(Name=Dict['InstallStatus']))
            if(Dict['StakerWorkOrderid']):
                stakerWorkOrder=COOPGIS_Misc.GetOneOrNone(staker.StakerWorkOrder.objects.filter(id=Dict['StakerWorkOrderid']))
            elif(Dict['StakerWorkOrderIndexWhenReverseSorted'] <> -1):
                stakerWorkOrder=staker.StakerWorkOrder.objects.all().order_by('-id')[Dict['StakerWorkOrderIndexWhenReverseSorted']]
            else:
                stakerWorkOrder=None
            Rotation=Dict['Rotation']
            if(not Rotation):
                Rotation=360
            try:
                transformerBank=GetObjectFromidandReverseSortedIndex('TransformerBank', djangoproject.models.compatibleunit.TransformerBank, Dict)
            except KeyError:
                transformerBank=None #Do not change the transformerbank if this key is not provided.
            assembly=compatibleunit.Assembly()
            assembly=assembly.GetOrCreate(compatibleUnit, 1, Station=StartStation, TagNumber=self.TagNumber, 
                                PutIntoServiceDate=Dict['PutIntoServiceDate'], 
                                PrimaryIndicator=Dict['PrimaryIndicator'], SecondaryIndicator=Dict['SecondaryIndicator'], 
                                IdleIndicator=Dict['IdleIndicator'], PhysicalAddress=Dict['PhysicalAddress'], 
                                PoleStubIndicator=Dict['PoleStubIndicator'], PoleLightIndicator=Dict['PoleLightIndicator'], 
                                PoleMeterIndicator=Dict['PoleMeterIndicator'],
                                assemblyOwner=owner, Manufacturer=manufacturer, meterForm=meterForm, OpenIndicator=Dict['OpenIndicator'], 
                                Rotation=Rotation, MeterOnPoleIndicator=Dict['MeterOnPoleIndicator'], PhaseAIndicator=Dict['PhaseAIndicator'],
                                PhaseBIndicator=Dict['PhaseBIndicator'], PhaseCIndicator=Dict['PhaseCIndicator'], 
                                PhaseNeutralIndicator=Dict['PhaseNeutralIndicator'], CircuitNumber=Dict['CircuitNumber'], 
                                SerialNumber=Dict['SerialNumber'], MeterNumber=Dict['MeterNumber'], 
                                MeterDCSINumber=Dict['MeterDCSINumber'],
                                OldMapNumber=Dict['OldMapNumber'], MapNumber=Dict['MapNumber'],
                                ServiceIndicator=Dict['ServiceIndicator'], CreateDate=self.CommandCreateDateTime, 
                                MeterServiceType=meterServiceType, CreateCommand=self, InstallStatus=installStatus, 
                                StakerWorkOrder=stakerWorkOrder, StakerRecipeNumber=Dict['StakerRecipeNumber'], transformerBank=transformerBank)
            if(RebuildSymbologyIndicator):
                StartStation.RebuildSymbology()
            ReturnObject=assembly
        elif(self.Name=='EditAssembly'):
            assembly=compatibleunit.Assembly.objects.filter(id__exact=Dict['Assemblyid'])[0]
            if(Dict.has_key('MeterServiceTypeName')):
                meterServiceType=COOPGIS_Misc.GetOneOrNone(compatibleunit.MeterServiceType.objects.filter(Name__exact=Dict['MeterServiceTypeName']))
            else:
                meterServiceType=None  
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            if(Dict.has_key('OwnerName')):
                owner=COOPGIS_Misc.GetOneOrNone(compatibleunit.AssemblyOwner.objects.filter(Name=Dict['OwnerName']))
            else:
                owner=None
            if(Dict.has_key('ManufacturerName')):
                manufacturer=COOPGIS_Misc.GetOneOrNone(compatibleunit.Company.objects.filter(Name=Dict['ManufacturerName']))
            else:
                manufacturer=None
            if(Dict.has_key('MeterFormName')):
                meterForm=COOPGIS_Misc.GetOneOrNone(compatibleunit.MeterForm.objects.filter(Name=Dict['MeterFormName']))
            else:
                meterForm=None
            installStatus=COOPGIS_Misc.GetOneOrNone(staker.InstallStatus.objects.filter(Name=Dict['InstallStatus']))
            assembly.CompatibleUnit=compatibleUnit
            if(Dict.has_key('PutIntoServiceDate')):
                assembly.PutIntoServiceDate=Dict['PutIntoServiceDate']
            else:
                assembly.PutIntoServiceDate=None
            assembly.PrimaryIndicator=Dict['PrimaryIndicator']
            assembly.SecondaryIndicator=Dict['SecondaryIndicator']
            assembly.PhaseAIndicator=Dict['PhaseAIndicator']
            assembly.PhaseBIndicator=Dict['PhaseBIndicator']
            assembly.PhaseCIndicator=Dict['PhaseCIndicator']
            assembly.PhaseNeutralIndicator=Dict['PhaseNeutralIndicator']
            assembly.IdleIndicator=Dict['IdleIndicator']
            if(Dict.has_key('PhysicalAddress')):
                assembly.PhysicalAddress=Dict['PhysicalAddress']
            else:
                assembly.PhysicalAddress=''
            assembly.CircuitNumber=Dict['CircuitNumber']
            if(assembly.Station):
                assembly.SerialNumber=Dict['SerialNumber']
                assembly.MeterNumber=Dict['MeterNumber']
                assembly.MeterDCSINumber=Dict['MeterDCSINumber']
                try:
                    assembly.MapNumber=int(Dict['MapNumber'])
                except:
                    assembly.MapNumber=None
                assembly.OldMapNumber=Dict['OldMapNumber']
                assembly.MeterServiceType=meterServiceType
                assembly.PoleStubIndicator=Dict['PoleStubIndicator']
                assembly.PoleLightIndicator=Dict['PoleLightIndicator']
                assembly.TagNumber=self.TagNumber
                assembly.AssemblyOwner=owner
                assembly.Manufacturer=manufacturer
                assembly.MeterForm=meterForm
                assembly.OpenIndicator=Dict['OpenIndicator']    
                assembly.MeterOnPoleIndicator=Dict['MeterOnPoleIndicator']
            if(Dict.has_key('Rotation')):
                assembly.Rotation=Dict['Rotation']
            else:
                assembly.Rotation=360
            try:
                assembly.TransformerBank=GetObjectFromidandReverseSortedIndex('TransformerBank', djangoproject.models.compatibleunit.TransformerBank, Dict)
            except KeyError:
                pass #Do not change the transformerbank if this key is not provided.
            assembly.ServiceIndicator=Dict['ServiceIndicator']
            assembly.CreateDate=self.CommandCreateDateTime
            assembly.CreateCommand=self
            assembly.InstallStatus=installStatus
            if(Dict.has_key('StakerWorkOrderid') and Dict['StakerWorkOrderid']):
                stakerWorkOrder=COOPGIS_Misc.GetOneOrNone(staker.StakerWorkOrder.objects.filter(id=Dict['StakerWorkOrderid']))
            elif(Dict.has_key('StakerWorkOrderIndexWhenReverseSorted') and (Dict['StakerWorkOrderIndexWhenReverseSorted'] <> None and Dict['StakerWorkOrderIndexWhenReverseSorted'] <> -1)):
                stakerWorkOrder=staker.StakerWorkOrder.objects.all().order_by('-id')[Dict['StakerWorkOrderIndexWhenReverseSorted']]
            else:
                stakerWorkOrder=None
            if(Dict.has_key('StakerRecipeNumber')):
                assembly.StakerRecipeNumber=Dict['StakerRecipeNumber']
            assembly.StakerWorkOrder=stakerWorkOrder
            assembly.save()
            if(assembly.Station):
                assembly.Station.RebuildSymbology()
            else:
                assembly.Span.RebuildSymbology()
            ReturnObject=assembly
        elif(self.Name=='EditAssemblyCircuit'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            else:
                assembly=None
            assembly.CompatibleUnit=djangoproject.models.compatibleunit.CompatibleUnit.objects.filter(id=Dict['CompatibleUnitid'])[0]
            assembly.TransformerCutOutIndicator=Dict['TransformerCutOutIndicator']
            assembly.OpenIndicator=Dict['OpenIndicator']
            if(not assembly.OpenIndicator):
                assembly.OpenIndicator=False
            assembly.PhaseAIndicator=Dict['PhaseAIndicator']
            assembly.PhaseBIndicator=Dict['PhaseBIndicator']
            assembly.PhaseCIndicator=Dict['PhaseCIndicator']
            assembly.PhaseNeutralIndicator=Dict['PhaseNeutralIndicator']
            assembly.CircuitNumber=Dict['CircuitNumber']
            assembly.BypassAssembly=GetObjectFromidandReverseSortedIndex('BypassAssembly', djangoproject.models.compatibleunit.Assembly, Dict)
            assembly.BypassIndicator=Dict['BypassIndicator']
            assembly.save()
            if(assembly.Station):
                assembly.Station.RebuildSymbology()
            else:
                assembly.Span.RebuildSymbology()
            ReturnObject=assembly 
        elif(self.Name=='UpdatePoleRightOfWayStatus'):
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            Poles=compatibleunit.Assembly.objects.filter(Station=StartStation, CompatibleUnit__PoleIndicator=True)
            poleRightOfWayStatus=compatibleunit.PoleRightOfWayStatus.objects.filter(Name=Dict['PoleRightOfWayStatusName'])[0]
            ReturnObject=False
            for i in Poles:
                i.PoleRightOfWayStatus=poleRightOfWayStatus
                i.save()
                StartStation.RebuildSymbology()      
            ReturnObject=poleRightOfWayStatus      
        elif(self.Name=='CreatePoleJointUse'):
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            poleJointUseType=compatibleunit.PoleJointUseType.objects.filter(Name=Dict['PoleJointUseTypeName'])[0]
            poleJointUseCompany=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            poleJointUse=compatibleunit.PoleJointUse()
            poleJointUse.Station=StartStation
            poleJointUse.PoleJointUseType=poleJointUseType
            poleJointUse.Company=poleJointUseCompany
            poleJointUse.Quantity=1
            poleJointUse.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            poleJointUse.CreateCommand=self
            poleJointUse.save()
            StartStation.RebuildSymbology()
            ReturnObject=poleJointUse
        elif(self.Name=='DeletePoleJointUse'):
            poleJointUse=compatibleunit.PoleJointUse.objects.filter(id__exact=Dict['PoleJointUseid'])[0]
            StartStation=geography.Station().GetOrCreateClosestStation(poleJointUse.Station.Point)
            poleJointUse.delete()
            StartStation.RebuildSymbology()
            ReturnObject='Deleted'
        elif(self.Name=='DeletePoleTreatment'):
            poleTreatment=compatibleunit.PoleTreatment.objects.filter(id__exact=Dict['PoleTreatmentid'])[0]
            StartStation=geography.Station().GetOrCreateClosestStation(poleTreatment.Pole.Station.Point)
            poleTreatment.delete()
            StartStation.RebuildSymbology()
            ReturnObject='Deleted'
        elif(self.Name=='DeleteAssembly'):
            assembly=compatibleunit.Assembly.objects.filter(id__exact=Dict['Assemblyid'])[0]
            if(assembly.Station):
                StationOrSpan=assembly.Station
            elif(assembly.Span):
                StationOrSpan=assembly.Span
            compatibleunit.PoleTreatment.objects.filter(Pole=assembly).delete()
            assembly.delete()
            StationOrSpan.RebuildSymbology()
            ReturnObject='Deleted'
        elif(self.Name=='CreatePoleTreatment'):  
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            pole=compatibleunit.Assembly.objects.filter(Station=StartStation, CompatibleUnit__PoleIndicator=True)[0]
            poleTreatment=compatibleunit.PoleTreatment()
            poleTreatment.Pole=pole
            poleTreatment.PoleTreatmentType=compatibleunit.PoleTreatmentType.objects.filter(Name=Dict['PoleTreatmentTypeName'])[0]
            poleTreatment.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            poleTreatment.PoleTreatmentDate=Dict['PoleTreatmentDate']
            poleTreatment.CreateCommand=self
            poleTreatment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            poleTreatment.CreateDateTime=self.CommandCreateDateTime
            poleTreatment.LastModifyDateTime=self.CommandCreateDateTime
            poleTreatment.CreateUserName=self.CommandUserName
            poleTreatment.LastModifyUserName=self.CommandUserName
            poleTreatment.save()
            StartStation.RebuildSymbology()
            ReturnObject=poleTreatment
        elif(self.Name=='CreatePoleTreatmentFull'):
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            pole=compatibleunit.Assembly.objects.filter(Station=StartStation, CompatibleUnit__PoleIndicator=True)[0]
            poleTreatment=compatibleunit.PoleTreatment()
            poleTreatment.Pole=pole
            poleTreatment.PoleTreatmentType=compatibleunit.PoleTreatmentType.objects.filter(Name=Dict['PoleTreatmentTypeName'])[0]
            poleTreatment.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            if(not Dict['PoleTreatmentDate']):
                Dict['PoleTreatmentDate']=COOPGIS_String.StringDateTimeToDateTime('1950')
            poleTreatment.PoleTreatmentDate=Dict['PoleTreatmentDate']
            poleTreatment.Description=Dict['Description']
            poleTreatment.CreateCommand=self
            poleTreatment.BrokenGuyIndicator=Dict['BrokenGuyIndicator']
            poleTreatment.BrokenInsulatorIndicator=Dict['BrokenInsulatorIndicator']
            poleTreatment.VisualInspectionIndicator=Dict['VisualInspectionIndicator']
            poleTreatment.VisualInspectionAndExcavationIndicator=Dict['VisualInspectionAndExcavationIndicator']
            poleTreatment.InternalTreatmentIndicator=Dict['InternalTreatmentIndicator']
            poleTreatment.InternalVoidTreatmentIndicator=Dict['InternalVoidTreatmentIndicator']
            poleTreatment.LightningArrestorBlownIndicator=Dict['LightningArrestorBlownIndicator']
            poleTreatment.NewPoleIndicator=Dict['NewPoleIndicator']
            poleTreatment.PoleLeaningIndicator=Dict['PoleLeaningIndicator']
            poleTreatment.SplitTopIndicator=Dict['SplitTopIndicator']
            poleTreatment.InternalDecayTreatmentIndicator=Dict['InternalDecayTreatmentIndicator']
            poleTreatment.WoodpeckerHolesIndicator=Dict['WoodpeckerHolesIndicator']
            poleTreatment.WireNeutralLowIndicator=Dict['WireNeutralLowIndicator']
            poleTreatment.WirePrimaryLowIndicator=Dict['WirePrimaryLowIndicator']
            poleTreatment.WireSecondaryLowIndicator=Dict['WireSecondaryLowIndicator']
            poleTreatment.RotIndicator=Dict['RotIndicator']
            poleTreatment.GroundlineTreatmentIndicator=Dict['GroundlineTreatmentIndicator']
            poleTreatment.RejectedIndicator=Dict['RejectedIndicator']
            poleTreatment.RepairedGroundIndicator=Dict['RepairedGroundIndicator']
            poleTreatment.BrokenCrossarmIndicator=Dict['BrokenCrossarmIndicator']
            poleTreatment.GuyMarkerReplacedQuantity=Dict['GuyMarkerReplacedQuantity']
            poleTreatment.GuyMarkerTotalQuantity=Dict['GuyMarkerTotalQuantity']
            poleTreatment.DataRecordOnlyIndicator=Dict['DataRecordOnlyIndicator']
            poleTreatment.Description=Dict['Description']
            poleTreatment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            poleTreatment.CreateDateTime=self.CommandCreateDateTime
            poleTreatment.LastModifyDateTime=self.CommandCreateDateTime
            poleTreatment.CreateUserName=self.CommandUserName
            poleTreatment.LastModifyUserName=self.CommandUserName
            poleTreatment.save()
            StartStation.RebuildSymbology()
            ReturnObject=poleTreatment
        elif(self.Name=='EditPoleTreatmentFull'):
            poleTreatment=compatibleunit.PoleTreatment.objects.filter(id=Dict['PoleTreatmentid'])[0]
            poleTreatment.PoleTreatmentType=compatibleunit.PoleTreatmentType.objects.filter(Name=Dict['PoleTreatmentTypeName'])[0]
            poleTreatment.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            if(not Dict['PoleTreatmentDate']):
                Dict['PoleTreatmentDate']=COOPGIS_String.StringDateTimeToDateTime('1950')
            poleTreatment.PoleTreatmentDate=Dict['PoleTreatmentDate']
            poleTreatment.Description=Dict['Description']
            poleTreatment.CreateCommand=self
            poleTreatment.BrokenGuyIndicator=Dict['BrokenGuyIndicator']
            poleTreatment.BrokenInsulatorIndicator=Dict['BrokenInsulatorIndicator']
            poleTreatment.VisualInspectionIndicator=Dict['VisualInspectionIndicator']
            poleTreatment.VisualInspectionAndExcavationIndicator=Dict['VisualInspectionAndExcavationIndicator']
            poleTreatment.InternalTreatmentIndicator=Dict['InternalTreatmentIndicator']
            poleTreatment.InternalVoidTreatmentIndicator=Dict['InternalVoidTreatmentIndicator']
            poleTreatment.LightningArrestorBlownIndicator=Dict['LightningArrestorBlownIndicator']
            poleTreatment.NewPoleIndicator=Dict['NewPoleIndicator']
            poleTreatment.PoleLeaningIndicator=Dict['PoleLeaningIndicator']
            poleTreatment.SplitTopIndicator=Dict['SplitTopIndicator']
            poleTreatment.InternalDecayTreatmentIndicator=Dict['InternalDecayTreatmentIndicator']
            poleTreatment.WoodpeckerHolesIndicator=Dict['WoodpeckerHolesIndicator']
            poleTreatment.WireNeutralLowIndicator=Dict['WireNeutralLowIndicator']
            poleTreatment.WirePrimaryLowIndicator=Dict['WirePrimaryLowIndicator']
            poleTreatment.WireSecondaryLowIndicator=Dict['WireSecondaryLowIndicator']
            poleTreatment.RotIndicator=Dict['RotIndicator']
            poleTreatment.GroundlineTreatmentIndicator=Dict['GroundlineTreatmentIndicator']
            poleTreatment.RejectedIndicator=Dict['RejectedIndicator']
            poleTreatment.RepairedGroundIndicator=Dict['RepairedGroundIndicator']
            poleTreatment.BrokenCrossarmIndicator=Dict['BrokenCrossarmIndicator']
            poleTreatment.GuyMarkerReplacedQuantity=Dict['GuyMarkerReplacedQuantity']
            poleTreatment.GuyMarkerTotalQuantity=Dict['GuyMarkerTotalQuantity']
            poleTreatment.DataRecordOnlyIndicator=Dict['DataRecordOnlyIndicator']
            poleTreatment.Description=Dict['Description']
            poleTreatment.LastModifyDateTime=self.CommandCreateDateTime
            poleTreatment.LastModifyUserName=self.CommandUserName
            poleTreatment.save()
            poleTreatment.Pole.Station.RebuildSymbology()
        elif(self.Name=='CreateSpanAssembly'):
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            EndStation=geography.Station().GetOrCreateClosestStation(self.EndPoint)
            span=geography.Span()
            MatchingSpans=span.GetAllMatching(StartStation, EndStation)
            if(not len(MatchingSpans) == 1):
                raise(Exception(str(self.id) + ":  " + "Could create an assembly in a span, # of Spans found was:  " + str(len(MatchingSpans))))
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            installStatus=COOPGIS_Misc.GetOneOrNone(staker.InstallStatus.objects.filter(Name=Dict['InstallStatus']))
            if(Dict['StakerWorkOrderid']):
                stakerWorkOrder=COOPGIS_Misc.GetOneOrNone(staker.StakerWorkOrder.objects.filter(id=Dict['StakerWorkOrderid']))
            elif(Dict['StakerWorkOrderIndexWhenReverseSorted'] <> None and Dict['StakerWorkOrderIndexWhenReverseSorted'] <> -1):
                stakerWorkOrder=staker.StakerWorkOrder.objects.all().order_by('-id')[Dict['StakerWorkOrderIndexWhenReverseSorted']]
            else:
                stakerWorkOrder=None
            assembly=compatibleunit.Assembly()
            assembly=assembly.GetOrCreate(compatibleUnit, 1, Span=MatchingSpans[0], PhaseAIndicator=Dict['PhaseAIndicator'], PhaseBIndicator=Dict['PhaseBIndicator'],
                                 PhaseCIndicator=Dict['PhaseCIndicator'], PhaseNeutralIndicator=Dict['PhaseNeutralIndicator'],CircuitNumber=Dict['CircuitNumber'],
                                 PrimaryIndicator=Dict['PrimaryIndicator'], SecondaryIndicator=Dict['SecondaryIndicator'], ServiceIndicator=Dict['ServiceIndicator'],
                                 CreateDate=self.CommandCreateDateTime, CreateCommand=self, InstallStatus=installStatus, IdleIndicator=Dict['IdleIndicator'],
                                 StakerWorkOrder=stakerWorkOrder, StakerRecipeNumber=Dict['StakerRecipeNumber'])
            MatchingSpans[0].RebuildSymbology()
            ReturnObject=assembly
        elif(self.Name=='DeleteStationAssembly'):
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            assembly = compatibleunit.Assembly.objects.filter(Station=StartStation).filter(CompatibleUnit=compatibleUnit)[0]
            ProtectingAssemblies=compatibleunit.ProtectingAssembly.objects.filter(Assembly=assembly)
            for i in ProtectingAssemblies:   
                i.delete()
            assembly.delete()
            ReturnObject=True
            StartStation.RebuildSymbology()
        elif(self.Name=='DeleteSpanAssembly'):
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            EndStation=geography.Station().GetOrCreateClosestStation(self.EndPoint)
            MatchingSpans=geography.Span().GetAllMatching(StartStation, EndStation)
            assembly=compatibleunit.Assembly.objects.filter(Span=MatchingSpans[0]).filter(CompatibleUnit=compatibleUnit)[0]
            assembly.delete()
            ReturnObject=True
            MatchingSpans[0].RebuildSymbology()
        elif(self.Name=='CreateCompatibleUnit'):
            try:
                compatibleUnitCategory=COOPGIS_Misc.GetOneOrNone(compatibleunit.CompatibleUnitCategory.objects.filter(id=int(Dict['CompatibleUnitCategoryid'])))
            except:
                compatibleUnitCategory=None
            InputVoltageid=Dict['InputVoltageid']
            try:
                inputVoltage=COOPGIS_Misc.GetOneOrNone(compatibleunit.Voltage.objects.filter(id=int(Dict['InputVoltageid'])))
            except:
                inputVoltage=None
            FirstOutputVoltageid=Dict['FirstOutputVoltageid']
            try:
                firstOutputVoltage=COOPGIS_Misc.GetOneOrNone(compatibleunit.Voltage.objects.filter(id=int(Dict['FirstOutputVoltageid'])))
            except:
                firstOutputVoltage=None
            SecondOutputVoltageid=Dict['SecondOutputVoltageid']
            try:
                secondOutputVoltage=COOPGIS_Misc.GetOneOrNone(compatibleunit.Voltage.objects.filter(id=int(Dict['SecondOutputVoltageid'])))
            except:
                secondOutputVoltage=None
            compatibleunit.CompatibleUnit().GetOrModify(Name=Dict['CompatibleUnitName'], Description=Dict['Description'], CompatibleUnitCategory=compatibleUnitCategory, 
                    KVA=Dict['KVA'], KVAR=Dict['KVAR'], InputVoltage=inputVoltage, FirstOutputVoltage=firstOutputVoltage, SecondOutputVoltage=secondOutputVoltage,
                    MaximumContinousAmp=Dict['MaximumContinousAmp'], Wattage=Dict['Wattage'],
                    Height=Dict['Height'], Class=Dict['Class'], LaborHours=Dict['LaborHours'], StationIndicator=Dict['StationIndicator'], SpanIndicator=Dict['SpanIndicator'],
                    ConductorIndicator=Dict['ConductorIndicator'], ConduitIndicator=Dict['ConduitIndicator'],
                    CapacitorIndicator=Dict['CapacitorIndicator'], CutOutIndicator=Dict['CutOutIndicator'], FeederIndicator=Dict['FeederIndicator'], 
                    GroundIndicator=Dict['GroundIndicator'], LightIndicator=Dict['LightIndicator'], LightningArrestorIndicator=Dict['LightningArrestorIndicator'],
                    OpenPointIndicator=Dict['OpenPointIndicator'], 
                    MiscellaneousEquipmentIndicator=Dict['MiscellaneousEquipmentIndicator'], PoleIndicator=Dict['PoleIndicator'],
                    RecloserIndicator=Dict['RecloserIndicator'], RegulatorIndicator=Dict['RegulatorIndicator'], 
                    MeterIndicator=Dict['MeterIndicator'], SpanGuyIndicator=Dict['SpanGuyIndicator'],
                    SubstationIndicator=Dict['SubstationIndicator'], SwitchIndicator=Dict['SwitchIndicator'],
                    TransformerIndicator=Dict['TransformerIndicator'], VaultIndicator=Dict['VaultIndicator'],
                    StakerPoleIndicator=Dict['StakerPoleIndicator'], 
                    StakerTransformerIndicator=Dict['StakerTransformerIndicator'], StakerMiscEquipmentIndicator=Dict['StakerMiscEquipmentIndicator'],
                    StakerGroundIndicator=Dict['StakerGroundIndicator'], StakerGuyGuyIndicator=Dict['StakerGuyGuyIndicator'], StakerGuyMarkerIndicator=Dict['StakerGuyMarkerIndicator'],
                    StakerGuyAnchorIndicator=Dict['StakerGuyAnchorIndicator'], StakerUnitIndicator=Dict['StakerUnitIndicator'], 
                    StakerSpanAssemblyIndicator=Dict['StakerSpanAssemblyIndicator'])
            ReturnObject=True
        elif(self.Name=='CreateStakerWorkOrder'):  
            stakerWorkOrder=staker.StakerWorkOrder()
            if(Dict.has_key('EstimateOnlyIndicator')):
                EstimateOnlyIndicator=Dict['EstimateOnlyIndicator']
            else:
                EstimateOnlyIndicator=False
            if(Dict.has_key('StationSortByDistanceIndicator')):
                StationSortByDistanceIndicator=Dict['StationSortByDistanceIndicator']
            else:
                StationSortByDistanceIndicator=False

            stakerWorkOrder = stakerWorkOrder.GetOrCreate(Name=Dict['StakerWorkOrderName'], UserName=self.CommandUserName, 
                                        Description=Dict['Description'], 
                                        HazardsAssociatedWithJobIndicator=Dict['HazardsAssociatedWithJobIndicator'], 
                                        WorkProcedureInvolvedIndicator=Dict['WorkProcedureInvolvedIndicator'],
                                        SpecialPrecautionsIndicator=Dict['SpecialPrecautionsIndicator'], 
                                        EnergySourceControlsIndicator=Dict['EnergySourceControlsIndicator'], 
                                        PPERequirementsIndicator=Dict['PPERequirementsIndicator'], 
                                        TailgateDiscussionIndicator=Dict['TailgateDiscussionIndicator'],
                                        CheckWhereSepticTankIsIndicator=Dict['CheckWhereSepticTankIsIndicator'], 
                                        WorkPlanReferenceIndicator=Dict['WorkPlanReferenceIndicator'], 
                                        NewConstructionIndicator=Dict['NewConstructionIndicator'], 
                                        SystemImprovementIndicator=Dict['SystemImprovementIndicator'], 
                                        ReplacementIndicator=Dict['ReplacementIndicator'], 
                                        Retire_No_ReplacementIndicator=Dict['Retire_No_ReplacementIndicator'],
                                        GeneralFundsIndicator=Dict['GeneralFundsIndicator'], 
                                        No_OfServicesOH=Dict['No_OfServicesOH'], No_OfServicesUG=Dict['No_OfServicesUG'],
                                        Wire=Dict['Wire'], LoanNo=Dict['LoanNo'], Substation=Dict['Substation'], MapNo=Dict['MapNo'], 
                                        LocationNextTo=Dict['LocationNextTo'], CalhounCountyIndicator=Dict['CalhounCountyIndicator'],
                                        OrangeburgCountyIndicator=Dict['OrangeburgCountyIndicator'], 
                                        LexingtonCountyIndicator=Dict['LexingtonCountyIndicator'],
                                        RichlandCountyIndicator=Dict['RichlandCountyIndicator'], 
                                        KershawCountyIndicator=Dict['KershawCountyIndicator'], 
                                        SumterCountyIndicator=Dict['SumterCountyIndicator'], 
                                        WorkOrderNumber=Dict['WorkOrderNumber'], W_P=Dict['W_P'], N_W_P=Dict['N_W_P'], 
                                        EngineerStaked=Dict['EngineerStaked'], EngineerChecked=Dict['EngineerChecked'], 
                                        EngineerReleasedForConst=Dict['EngineerReleasedForConst'], Co_PermitNo=Dict['Co_PermitNo'], 
                                        PUPS=Dict['PUPS'], NewR_WIndicator=Dict['NewR_WIndicator'], R_WToBeCutIndicator=Dict['R_WToBeCutIndicator'], 
                                        R_WCutDate=Dict['R_WCutDate'], ExistingR_WIndicator=Dict['ExistingR_WIndicator'], 
                                        CreateDate=self.CommandCreateDateTime, 
                                        StakerPhaseStartIndicator=Dict['StakerPhaseStartIndicator'],
                                        StakerPhaseStartDate=Dict['StakerPhaseStartDate'], 
                                        OutToConstructionStartIndicator=Dict['OutToConstructionStartIndicator'], 
                                        OutToConstructionStartDate=Dict['OutToConstructionStartDate'], 
                                        VerificationPhaseStartIndicator=Dict['VerificationPhaseStartIndicator'], 
                                        VerificationPhaseStartDate=Dict['VerificationPhaseStartDate'],
                                        ArchivedIndicator=Dict['ArchivedIndicator'], ArchivedDate=Dict['ArchivedDate'], 
                                        DeletedIndicator=Dict['DeletedIndicator'], CreateCommand=self,
                                        MinimumX=Dict['MinimumX'], MinimumY=Dict['MinimumY'], MaximumX=Dict['MaximumX'], 
                                        MaximumY=Dict['MaximumY'], AutomaticallyRecalculateExtentsIndicator=Dict['AutomaticallyRecalculateExtentsIndicator'],
                                        StationListOverride=Dict['StationListOverride'], StationSortByDistanceIndicator=StationSortByDistanceIndicator,
                                        DisplayMapOutlineIndicator=Dict['DisplayMapOutlineIndicator'], EstimateOnlyIndicator=EstimateOnlyIndicator)
            ReturnObject=stakerWorkOrder
        elif(self.Name=='EditStakerWorkOrder'):
            stakerWorkOrder=staker.StakerWorkOrder.objects.filter(id__exact=Dict['StakerWorkOrderid'])[0]

            try:
                EstimateOnlyIndicator=Dict['EstimateOnlyIndicator']
            except:
                EstimateOnlyIndicator=False

            if(stakerWorkOrder.ArchivedIndicator):
                ReturnObject="Did Not Edit, already archived"
            else:
                stakerWorkOrder.Name=Dict['StakerWorkOrderName']
                if(Dict['ChangeUserNameIndicator']):
                    stakerWorkOrder.UserName=self.CommandUserName
                stakerWorkOrder.Description=Dict['Description']
                stakerWorkOrder.HazardsAssociatedWithJobIndicator=Dict['HazardsAssociatedWithJobIndicator']
                stakerWorkOrder.WorkProcedureInvolvedIndicator=Dict['WorkProcedureInvolvedIndicator']
                stakerWorkOrder.SpecialPrecautionsIndicator=Dict['SpecialPrecautionsIndicator'] 
                stakerWorkOrder.EnergySourceControlsIndicator=Dict['EnergySourceControlsIndicator'] 
                stakerWorkOrder.PPERequirementsIndicator=Dict['PPERequirementsIndicator'] 
                stakerWorkOrder.TailgateDiscussionIndicator=Dict['TailgateDiscussionIndicator']
                stakerWorkOrder.CheckWhereSepticTankIsIndicator=Dict['CheckWhereSepticTankIsIndicator'] 
                stakerWorkOrder.WorkPlanReferenceIndicator=Dict['WorkPlanReferenceIndicator'] 
                stakerWorkOrder.NewConstructionIndicator=Dict['NewConstructionIndicator'] 
                stakerWorkOrder.SystemImprovementIndicator=Dict['SystemImprovementIndicator'] 
                stakerWorkOrder.ReplacementIndicator=Dict['ReplacementIndicator'] 
                stakerWorkOrder.Retire_No_ReplacementIndicator=Dict['Retire_No_ReplacementIndicator']
                stakerWorkOrder.GeneralFundsIndicator=Dict['GeneralFundsIndicator']
                stakerWorkOrder.No_OfServicesOH=Dict['No_OfServicesOH'] 
                stakerWorkOrder.No_OfServicesUG=Dict['No_OfServicesUG']
                stakerWorkOrder.Wire=Dict['Wire'] 
                stakerWorkOrder.LoanNo=Dict['LoanNo'] 
                stakerWorkOrder.Substation=Dict['Substation']
                stakerWorkOrder.MapNo=Dict['MapNo']
                stakerWorkOrder.LocationNextTo=Dict['LocationNextTo']
                stakerWorkOrder.CalhounCountyIndicator=Dict['CalhounCountyIndicator']
                stakerWorkOrder.OrangeburgCountyIndicator=Dict['OrangeburgCountyIndicator'] 
                stakerWorkOrder.LexingtonCountyIndicator=Dict['LexingtonCountyIndicator']
                stakerWorkOrder.RichlandCountyIndicator=Dict['RichlandCountyIndicator']
                stakerWorkOrder.KershawCountyIndicator=Dict['KershawCountyIndicator'] 
                stakerWorkOrder.SumterCountyIndicator=Dict['SumterCountyIndicator'] 
                stakerWorkOrder.WorkOrderNumber=Dict['WorkOrderNumber']
                stakerWorkOrder.W_P=Dict['W_P'] 
                stakerWorkOrder.N_W_P=Dict['N_W_P']
                stakerWorkOrder.EngineerStaked=Dict['EngineerStaked']
                stakerWorkOrder.EngineerChecked=Dict['EngineerChecked'] 
                stakerWorkOrder.EngineerReleasedForConst=Dict['EngineerReleasedForConst']
                stakerWorkOrder.Co_PermitNo=Dict['Co_PermitNo'] 
                stakerWorkOrder.PUPS=Dict['PUPS']
                stakerWorkOrder.NewR_WIndicator=Dict['NewR_WIndicator']
                stakerWorkOrder.R_WToBeCutIndicator=Dict['R_WToBeCutIndicator'] 
                stakerWorkOrder.R_WCutDate=Dict['R_WCutDate']
                stakerWorkOrder.ExistingR_WIndicator=Dict['ExistingR_WIndicator'] 
                stakerWorkOrder.CreateDate=self.CommandCreateDateTime 
                stakerWorkOrder.StakerPhaseStartIndicator=Dict['StakerPhaseStartIndicator']
                stakerWorkOrder.StakerPhaseStartDate=Dict['StakerPhaseStartDate']
                stakerWorkOrder.OutToConstructionStartIndicator=Dict['OutToConstructionStartIndicator'] 
                stakerWorkOrder.OutToConstructionStartDate=Dict['OutToConstructionStartDate']
                stakerWorkOrder.VerificationPhaseStartIndicator=Dict['VerificationPhaseStartIndicator'] 
                stakerWorkOrder.VerificationPhaseStartDate=Dict['VerificationPhaseStartDate']
                stakerWorkOrder.ArchivedIndicator=Dict['ArchivedIndicator']
                stakerWorkOrder.ArchivedDate=Dict['ArchivedDate'] 
                stakerWorkOrder.DeletedIndicator=Dict['DeletedIndicator']
                stakerWorkOrder.MinimumX=Dict['MinimumX']
                stakerWorkOrder.MinimumY=Dict['MinimumY']
                stakerWorkOrder.MaximumX=Dict['MaximumX'] 
                stakerWorkOrder.MaximumY=Dict['MaximumY']
                stakerWorkOrder.AutomaticallyRecalculateExtentsIndicator=Dict['AutomaticallyRecalculateExtentsIndicator']
                stakerWorkOrder.StationListOverride=Dict['StationListOverride']
                stakerWorkOrder.StationSortByDistanceIndicator=Dict['StationSortByDistanceIndicator']
                stakerWorkOrder.DisplayMapOutlineIndicator=Dict['DisplayMapOutlineIndicator']
                stakerWorkOrder.EstimateOnlyIndicator=EstimateOnlyIndicator
                stakerWorkOrder.save()
                ReturnObject=stakerWorkOrder
        elif(self.Name=='DeleteStakerWorkOrder'):
            stakerWorkOrder=staker.StakerWorkOrder.objects.filter(id=Dict['StakerWorkOrderid'])[0]
            if(stakerWorkOrder.ArchivedIndicator):
                ReturnObject="Did Not Delete, already archived"
            else:
                if(stakerWorkOrder.OutToConstructionStartIndicator or stakerWorkOrder.VerificationPhaseStartIndicator or
                   stakerWorkOrder.ArchivedIndicator or stakerWorkOrder.DeletedIndicator):
                   ReturnObject=False
                else:
                    stakerWorkOrder.DeletedIndicator=True
                    stakerWorkOrder.save()
                    ReturnObject=stakerWorkOrder
        elif(self.Name=='UndeleteStakerWorkOrder'):
            stakerWorkOrder=staker.StakerWorkOrder()
            stakerWorkOrder=staker.StakerWorkOrder.objects.filter(id=Dict['StakerWorkOrderid'])[0]
            stakerWorkOrder.DeletedIndicator=False
            stakerWorkOrder.save()
            ReturnObject=stakerWorkOrder
        elif(self.Name=='CreateProtectingAssembly'):
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            EndStation=geography.Station().GetOrCreateClosestStation(self.EndPoint)
            MatchingSpan=geography.Span().GetAllMatching(StartStation, EndStation)[0]
            assembly = compatibleunit.Assembly.objects.filter(Station=StartStation).filter(CompatibleUnit=compatibleUnit).order_by('id')[Dict['IndexWhenSorted']]
            if(assembly):
                protectingAssembly=compatibleunit.ProtectingAssembly()
                protectingAssembly=protectingAssembly.GetOrCreate(span=MatchingSpan, assembly=assembly)
                StartStation.RebuildSymbology()
                EndStation.RebuildSymbology()
                ReturnObject=protectingAssembly
            else:
                ReturnObject=False
        elif(self.Name=='DeleteProtectingAssembly'):
            compatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=self.AssemblyName)[0]
            StartStation=geography.Station().GetOrCreateClosestStation(self.StartPoint)
            EndStation=geography.Station().GetOrCreateClosestStation(self.EndPoint)
            span=geography.Span()
            MatchingSpan=span.GetAllMatching(StartStation, EndStation)[0]
            assembly = compatibleunit.Assembly.objects.filter(Station=StartStation).filter(CompatibleUnit=compatibleUnit).order_by('id')[Dict['IndexWhenSorted']]
            if(assembly):
                protectingAssembly=compatibleunit.ProtectingAssembly.objects.filter(Span=MatchingSpan).filter(Assembly=assembly)
                protectingAssembly.delete()
                StartStation.RebuildSymbology()
                EndStation.RebuildSymbology()
                ReturnObject=protectingAssembly
            else:
                ReturnObject=False
        elif(self.Name=='CreateVegetationManagerJob'):
            vegetationManagerJob=djangoproject.models.vegetationmanager.VegetationManagerJob()
            vegetationManagerJob.Description = Dict['Description']
            vegetationManagerJob.VegetationManagerCrew=GetObjectFromidandReverseSortedIndex('VegetationManagerCrew', djangoproject.models.vegetationmanager.VegetationManagerCrew, Dict)
            vegetationManagerJob.WorkStartDate=Dict['WorkStartDate']
            vegetationManagerJob.WorkEndDate=Dict['WorkEndDate']
            vegetationManagerJob.CreateDate = self.CommandCreateDateTime.date()
            vegetationManagerJob.VegetationManagerJobStatus=GetObjectFromidandReverseSortedIndex('VegetationManagerJobStatus', djangoproject.models.vegetationmanager.VegetationManagerJobStatus, Dict)            
            vegetationManagerJob.HoursWorkedQuantity=Dict['HoursWorkedQuantity']
            vegetationManagerJob.WidthInFeet=Dict['WidthInFeet']
            vegetationManagerJob.ActiveIndicator=Dict['ActiveIndicator']
            vegetationManagerJob.SubstationName=Dict['SubstationName']
            vegetationManagerJob.CircuitName=Dict['CircuitName']
            vegetationManagerJob.TrimRightOfWayIndicator=Dict['TrimRightOfWayIndicator']
            vegetationManagerJob.ResidesOnServerIndicator = djangoproject.settings.COOPGISServerIndicator
            vegetationManagerJob.save()
            ReturnObject=vegetationManagerJob
        elif(self.Name=='EditVegetationManagerJob'):
            vegetationManagerJob=vegetationmanager.VegetationManagerJob.objects.filter(id=Dict['VegetationManagerJobid'])[0]
            vegetationManagerJob.Description=Dict['Description']
            vegetationManagerJob.VegetationManagerCrew=GetObjectFromidandReverseSortedIndex('VegetationManagerCrew', djangoproject.models.vegetationmanager.VegetationManagerCrew, Dict)
            vegetationManagerJob.WorkStartDate=Dict['WorkStartDate']
            vegetationManagerJob.WorkEndDate=Dict['WorkEndDate']
            vegetationManagerJob.VegetationManagerJobStatus=GetObjectFromidandReverseSortedIndex('VegetationManagerJobStatus', djangoproject.models.vegetationmanager.VegetationManagerJobStatus, Dict)
            vegetationManagerJob.HoursWorkedQuantity=Dict['HoursWorkedQuantity']
            vegetationManagerJob.WidthInFeet=Dict['WidthInFeet']
            vegetationManagerJob.ActiveIndicator=Dict['ActiveIndicator']
            #vegetationManagerJob.StakerWorkOrder=stakerWorkOrder
            vegetationManagerJob.TrimRightOfWayIndicator=Dict['TrimRightOfWayIndicator']
            vegetationManagerJob.SubstationName=Dict['SubstationName']
            vegetationManagerJob.CircuitName=Dict['CircuitName']
            vegetationManagerJob.save()
            VegetationManagerJobSpans=vegetationmanager.VegetationManagerJobSpan.objects.filter(VegetationManagerJob=vegetationManagerJob)
            #FIXME disabled jobspan symbology update for paper conversions
            #for vegetationManagerJobSpan in VegetationManagerJobSpans:
            #    vegetationManagerJobSpan.CalculateSymbologyFields()     
            #    vegetationManagerJobSpan.save()             
            ReturnObject=vegetationManagerJob
        elif(self.Name=='DeleteVegetationManagerJob'):
            vegetationManagerJob=vegetationmanager.VegetationManagerJob.objects.filter(id=Dict['VegetationManagerJobid'])[0]
            if(not vegetationmanager.VegetationManagerJobSpan.objects.filter(VegetationManagerJob=vegetationManagerJob)):
                vegetationManagerJob.delete()
                ReturnObject='Deleted Vegetation Manager Job'
            else:
                ReturnObject='VegetationJobSpans Exist, could not delete Vegetation Manager Job'
        elif(self.Name=='CreateVegetationManagerJobStatus'):
            if(vegetationmanager.VegetationManagerJobStatus.objects.filter(Name=Dict['VegetationManagerJobStatusName'])):
                ReturnObject='Could not Create Vegetation Manager Job Status, One with the Name:  ' + str(Dict['VegetationManagerJobStatusName']) + '  already exists.'
            else:
                vegetationManagerJobStatus=vegetationmanager.VegetationManagerJobStatus()
                vegetationManagerJobStatus.Name=Dict['VegetationManagerJobStatusName']
                vegetationManagerJobStatus.CreateCommand=self
                vegetationManagerJobStatus.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
                vegetationManagerJobStatus.save()
                ReturnObject=vegetationManagerJobStatus
        elif(self.Name=='EditVegetationManagerJobStatus'):
            vegetationManagerJobStatus=vegetationmanager.VegetationManagerJobStatus.objects.filter(id=Dict['VegetationManagerJobStatusid'])[0]
            vegetationManagerJobStatus.Name=Dict['VegetationManagerJobStatusName']
            vegetationManagerJobStatus.save()
            ReturnObject=vegetationManagerJobStatus
        elif(self.Name=='DeleteVegetationManagerJobStatus'):
            vegetationManagerJobStatus=vegetationmanager.VegetationManagerJobStatus.objects.filter(id=Dict['VegetationManagerJobStatusid'])[0]
            if(not vegetationmanager.VegetationManagerJob.objects.filter(VegetationManagerJobStatus=vegetationManagerJobStatus)):
                vegetationManagerJobStatus.delete()
                ReturnObject='Deleted Vegetation Manager Job Status'
            else:
                ReturnObject='Related VegetationManagementJobs Exist, could not delete Vegetation Manager Job Status'       
        elif(self.Name=='CreateVegetationManagerJobSpan'):
            span = djangoproject.models.vegetationmanager.VegetationManagerJobSpan()
            vegetationManagerJob = djangoproject.models.vegetationmanager.VegetationManagerJob.objects.filter(id=Dict['VegetationManagerJobid'])[0]
            span.VegetationManagerJob = vegetationManagerJob
            span.Line = Dict['Line']
            span.Spanid = Dict['Spanid']
            if vegetationManagerJob.WorkEndDate:
                span.WorkCompletedDate = vegetationManagerJob.WorkEndDate
            if Dict['SymbologyJobYear']:
                span.SymbologyJobYear = Dict['SymbologyJobYear']
            elif span.WorkCompletedDate:
                span.SymbologyJobYear = span.WorkCompletedDate.year
            span.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            span.save()
            ReturnObject=span
        elif(self.Name=='EditVegetationManagerJobSpan'):
            if(Dict['VegetationManagerJobid'] <> -1):
                vegetationManagerJob=vegetationmanager.VegetationManagerJob.objects.filter(id=Dict['VegetationManagerJobid'])[0]
            elif(Dict['VegetationManagerJobIndexWhenReverseSorted'] <> -1):
                vegetationManagerJob=vegetationmanager.VegetationManagerJob.objects.all().order_by('-id')[Dict['VegetationManagerJobIndexWhenReverseSorted']]
            vegetationManagerJobSpan=vegetationmanager.VegetationManagerJobSpan.objects.filter(VegetationManagerJob=vegetationManagerJob).filter(Line=self.Line)[0]
            duplicateVegetationManagerJobSpans=vegetationmanager.VegetationManagerJobSpan.objects.filter(Line=self.Line).filter(VegetationManagerJob=vegetationManagerJob)
            StopProcessingIndicator=False
            for i in duplicateVegetationManagerJobSpans:
                if(not (i == vegetationManagerJobSpan)):
                    ReturnObject='Could not Edit Vegetation Manager Job Span, edit would create a duplicate line for the same job'
                    StopProcessingIndicator=True
            if(not StopProcessingIndicator):
                vegetationManagerJobSpan.Line=self.Line
                if(Dict['WidthInFeet']):
                    vegetationManagerJobSpan.WidthInFeet=Dict['WidthInFeet']
                else:
                    vegetationManagerJobSpan.WidthInFeet=vegetationManagerJob.WidthInFeet
                vegetationManagerJobSpan.VegetationManagerJob=vegetationManagerJob
                vegetationManagerJobSpan.Spanid=Dict['VegetationManagerJobSpanid']
                vegetationManagerJobSpan.WorkCompletedDate=Dict['WorkCompletedDate']
                vegetationManagerJobSpan.CalculateSymbologyFields()
                vegetationManagerJobSpan.save()
                ReturnObject=vegetationManagerJobSpan
        elif(self.Name=='DeleteVegetationManagerJobSpan'):
            vegetationManagerJobSpan=vegetationmanager.VegetationManagerJobSpan.objects.filter(id=Dict['VegetationManagerJobSpanid'])[0]
            vegetationManagerJobSpan.delete()
            ReturnObject='Deleted Vegetation Manager Job Span'
        elif(self.Name=='CreateVegetationManagerCrew'):
            if(Dict['Companyid'] and Dict['Companyid'] <> -1):
                company=compatibleunit.Company.objects.filter(id=Dict['Companyid'])[0]
            elif(self.CompanyIndexWhenReverseSorted <> -1):
                company=compatibleunit.Company.objects.all().order_by('-id')[Dict['CompanyIndexWhenReverseSorted']]
            else:
                company=None
            vegetationManagerCrew=vegetationmanager.VegetationManagerCrew()
            vegetationManagerCrew.WorkerQuantity=Dict['WorkerQuantity']
            vegetationManagerCrew.Company=company
            vegetationManagerCrew.WorkStartDate=Dict['WorkStartDate']
            vegetationManagerCrew.WorkEndDate=Dict['WorkEndDate']
            vegetationManagerCrew.ActiveIndicator=Dict['ActiveIndicator']
            vegetationManagerCrew.RadioNumber=Dict['RadioNumber']
            vegetationManagerCrew.CreateCommand=self
            vegetationManagerCrew.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            vegetationManagerCrew.save()
            ReturnObject=vegetationManagerCrew
        elif(self.Name=='EditVegetationManagerCrew'):
            if(Dict['Companyid'] and Dict['Companyid'] <> -1):
                company=compatibleunit.Company.objects.filter(id=Dict['Companyid'])[0]
            elif(Dict['CompanyIndexWhenReverseSorted'] <> -1):
                company=compatibleunit.Company.objects.all().order_by('-id')[self.CompanyIndexWhenReverseSorted]
            else:
                company=None
            vegetationManagerCrew=vegetationmanager.VegetationManagerCrew.objects.filter(id=Dict['VegetationManagerCrewid'])[0]
            vegetationManagerCrew.WorkerQuantity=Dict['WorkerQuantity']
            vegetationManagerCrew.Company=company
            vegetationManagerCrew.WorkStartDate=Dict['WorkStartDate']
            vegetationManagerCrew.WorkEndDate=Dict['WorkEndDate']
            vegetationManagerCrew.ActiveIndicator=Dict['ActiveIndicator']
            vegetationManagerCrew.RadioNumber=Dict['RadioNumber']
            vegetationManagerCrew.save()
            ReturnObject=vegetationManagerCrew
        elif(self.Name=='DeleteVegetationManagerCrew'):
            vegetationManagerCrew=vegetationmanager.VegetationManagerCrew.objects.filter(id=Dict['VegetationManagerCrewid'])[0]
            if(not vegetationmanager.VegetationManagerJob.objects.filter(VegetationManagerCrew=vegetationManagerCrew)):
                vegetationManagerCrew.delete()
                ReturnObject='Deleted Vegetation Manager Crew'
            else:
                ReturnObject='Related Vegetation Management Jobs Exist, could not delete Vegetation Manager Crew'       
        elif(self.Name=='CreateCompany'):
            company=compatibleunit.Company()
            company.Name=Dict['ObjectName']
            company.Description=Dict['Description']
            company.PoleTreatmentIndicator=Dict['PoleTreatmentIndicator']
            company.PoleJointUseIndicator=Dict['PoleJointUseIndicator']
            company.ManufacturerIndicator=Dict['ManufacturerIndicator']
            if(Dict.has_key('VegetationManagementIndicator')):
                company.VegetationManagementIndicator=Dict['VegetationManagementIndicator'] 
            else:
                company.VegetationManagementIndicator=False
            company.ContractorIndicator=Dict['ContractorIndicator']
            company.GroundRodTestIndicator=Dict['GroundRodTestIndicator']
            company.CreateCommand=self
            company.save()
            ReturnObject=company
        elif(self.Name=='EditCompany'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                company=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['Objectid'])[0]
            else:
                company=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            company.Name=Dict['ObjectName']
            company.Description=Dict['Description']
            company.PoleTreatmentIndicator=Dict['PoleTreatmentIndicator']
            company.PoleJointUseIndicator=Dict['PoleJointUseIndicator']
            company.ManufacturerIndicator=Dict['ManufacturerIndicator']
            if(Dict.has_key('VegetationManagementIndicator')):
                company.VegetationManagementIndicator=Dict['VegetationManagementIndicator']
            else:
                company.VegetationManagementIndicator=False
            company.ContractorIndicator=Dict['ContractorIndicator']
            company.GroundRodTestIndicator=Dict['GroundRodTestIndicator']
            company.save()
            ReturnObject=company
        elif(self.Name=='DeleteCompany'):
            company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            if(compatibleunit.PoleTreatment.objects.filter(Company=company)):
                ReturnObject="A PoleTreatment object exists that references the company, cannot delete"
            elif(compatibleunit.PoleJointUse.objects.filter(Company=company)):
                ReturnObject="A PoleJointUse object exists that references the company, cannot delete"
            elif(vegetationmanager.VegetationManagerCrew.objects.filter(Company=company)):
                ReturnObject="A VegetationManagerCrew object exists that references the company, cannot delete"
            elif(compatibleunit.Assembly.objects.filter(Manufacturer=company)):
                ReturnObject='An Assembly Maufacturer exists that references the company, cannot delete'
            else:
                company.delete()
        elif(self.Name=='CreateCompatibleUnitPrice'):
            compatibleUnitPrice=compatibleunit.CompatibleUnitPrice()
            compatibleUnitPrice.CodedInstallPrice=Dict['CodedInstallPrice']
            compatibleUnitPrice.CodedRemovePrice=Dict['CodedRemovePrice']
            compatibleUnitPrice.Description=Dict['Description']
            compatibleUnitPrice.CompatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract.objects.filter(id=Dict['CompatibleUnitPriceContractid'])[0]
            compatibleUnitPrice.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            compatibleUnitPrice.CompatibleUnit=compatibleunit.CompatibleUnit.objects.filter(Name=Dict['CompatibleUnitName'])[0]
            compatibleUnitPrice.CreateCommand=self
            compatibleUnitPrice.save()
            ReturnObject=compatibleUnitPrice
        elif(self.Name=='EditCompatibleUnitPrice'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                compatibleUnitPrice=djangoproject.models.compatibleunit.CompatibleUnitPrice.objects.filter(id=Dict['Objectid'])[0]
            else:
                compatibleUnitPrice=djangoproject.models.compatibleunit.CompatibleUnitPrice.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            compatibleUnitPrice.CompatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract.objects.filter(id=Dict['CompatibleUnitPriceContractid'])[0]
            compatibleUnitPrice.CodedInstallPrice=Dict['CodedInstallPrice']
            compatibleUnitPrice.CodedRemovePrice=Dict['CodedRemovePrice']
            compatibleUnitPrice.save()
            ReturnObject=compatibleUnitPrice
        elif(self.Name=='DeleteCompatibleUnitPrice'):
            compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.filter(id=Dict['CompatibleUnitPriceid'])
            compatibleUnitPrice.delete()
            ReturnObject='Deleted a CompatibleUnitPrice'
        elif(self.Name=='CreateCompatibleUnitPriceContract'):
            compatibleUnitPriceContract=compatibleunit.CompatibleUnitPriceContract()
            compatibleUnitPriceContract.Name=Dict['ObjectName']
            compatibleUnitPriceContract.Description=Dict['Description']
            compatibleUnitPriceContract.ActiveIndicator=Dict['ActiveIndicator']
            compatibleUnitPriceContract.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            compatibleUnitPriceContract.StartDate=Dict['StartDate']
            compatibleUnitPriceContract.EndDate=Dict['EndDate']
            compatibleUnitPriceContract.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            compatibleUnitPriceContract.CreateCommand=self
            compatibleUnitPriceContract.save()
            ReturnObject=compatibleUnitPriceContract          
        elif(self.Name=='EditCompatibleUnitPriceContract'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                compatibleUnitPriceContract=djangoproject.models.compatibleunit.CompatibleUnitPriceContract.objects.filter(id=Dict['Objectid'])[0]
            else:
                compatibleUnitPriceContract=djangoproject.models.compatibleunit.CompatibleUnitPriceContract.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            compatibleUnitPriceContract.Name=Dict['ObjectName']
            compatibleUnitPriceContract.Description=Dict['Description']
            compatibleUnitPriceContract.StartDate=Dict['StartDate']
            compatibleUnitPriceContract.EndDate=Dict['EndDate']
            compatibleUnitPriceContract.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            compatibleUnitPriceContract.ActiveIndicator=Dict['ActiveIndicator']
            #raise(Exception('Made it to command'))
            compatibleUnitPriceContract.save()
            ReturnObject=compatibleUnitPriceContract
        elif(self.Name=='DeleteCompatibleUnitPriceContract'):
            CompatibleUnitPrices=compatibleunit.CompatibleUnitPrice.objects.filter(CompatibleUnitPriceContract__id=Dict['CompatibleUnitPriceContractid'])
            if(CompatibleUnitPrices):
                ReturnObject='Did Not Delete a CompatibleUnitPriceContract because related CompatibleUnitPrices Exist.'
            else:
                compatibleUnitPrice=compatibleunit.CompatibleUnitPrice.objects.filter(id=Dict['CompatibleUnitPriceContractid'])
                compatibleUnitPrice.delete()
                ReturnObject='Deleted a CompatibleUnitPriceContract'
        elif(self.Name=='CreateBoardDistrict'):
            boardDistrict=geography.BoardDistrict()
            boardDistrict.Name=Dict['ObjectName']
            boardDistrict.Description=Dict['Description']
            boardDistrict.Polygon=self.Polygon
            boardDistrict.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            boardDistrict.CreateCommand=self
            boardDistrict.save()
            ReturnObject=boardDistrict
        elif(self.Name=='EditBoardDistrict'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                boardDistrict=geography.BoardDistrict.objects.filter(id=Dict['Objectid'])[0]
            else:
                boardDistrict=geography.BoardDistrict.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            boardDistrict.Name=Dict['ObjectName']
            boardDistrict.Description=Dict['Description']
            if(self.Polygon):
                boardDistrict.Polygon=self.Polygon
            boardDistrict.save()
            ReturnObject=boardDistrict
        elif(self.Name=='DeleteBoardDistrict'):
            boardDistrict=geography.BoardDistrict.objects.filter(id=Dict['Objectid'])
            boardDistrict.delete()
            ReturnObject='Deleted a BoardDistrict'
        #temporarily hard-coded to work with polygons only  
        elif(self.Name=='CreateLandmarkType'):
            landmarkType=geography.LandmarkType()
            landmarkType.Name=Dict['ObjectName']
            landmarkType.Description=Dict['Description']
            landmarkType.PointIndicator=Dict['PointIndicator']
            landmarkType.LineIndicator=Dict['LineIndicator']
            landmarkType.PolygonIndicator=Dict['PolygonIndicator']
            landmarkType.CreateCommand=self
            landmarkType.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            landmarkType.save()
            ReturnObject=landmarkType
        elif(self.Name=='EditLandmarkType'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            else:
                landmarkType=None
            landmarkType.Name=Dict['ObjectName']
            landmarkType.Description=Dict['Description']
            landmarkType.PointIndicator=Dict['PointIndicator']
            landmarkType.LineIndicator=Dict['LineIndicator']
            landmarkType.PolygonIndicator=Dict['PolygonIndicator']
            landmarkType.CreateCommand=self
            landmarkType.save()
            ReturnObject=landmarkType
        elif(self.Name=='DeleteLandmarkType'):
            landmarkType=geography.LandmarkType.objects.filter(id=Dict['Objectid'])
            landmarkType.delete()
            ReturnObject='Deleted a LandmarkType'
        elif(self.Name=='CreateLandmarkPoint'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None
            landmarkPoint=geography.LandmarkPoint()
            landmarkPoint.Name=Dict['ObjectName']
            landmarkPoint.Description=Dict['Description']
            landmarkPoint.Point=self.StartPoint
            landmarkPoint.LandmarkType=landmarkType
            landmarkPoint.CreateCommand=self
            landmarkPoint.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            landmarkPoint.SymbologyText = None
            landmarkPoint.save()
            landmarkPoint.SymbologyText = geography.GenerateLandmarkSymbologyTextValue(landmarkPoint)
            landmarkPoint.save()
            ReturnObject=landmarkPoint
        elif(self.Name=='EditLandmarkPoint'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None

            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                landmarkPoint=djangoproject.models.geography.LandmarkPoint.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                landmarkPoint=djangoproject.models.geography.LandmarkPoint.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            else:
                landmarkPoint=None
            landmarkPoint.Name=Dict['ObjectName']
            landmarkPoint.Description=Dict['Description']
            landmarkPoint.LandmarkType=landmarkType
            landmarkPoint.Point=self.StartPoint
            landmarkPoint.CreateCommand=self
            landmarkPoint.SymbologyText = geography.GenerateLandmarkSymbologyTextValue(landmarkPoint)
            landmarkPoint.save()
            ReturnObject=landmarkPoint
        elif(self.Name=='DeleteLandmarkPoint'):
            landmarkPoint=geography.LandmarkPoint.objects.filter(id=Dict['Objectid'])
            landmarkPoint.delete()
            ReturnObject='Deleted a LandmarkPoint'
        elif(self.Name=='CreateLandmarkLine'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None
            landmarkLine=geography.LandmarkLine()
            landmarkLine.Name=Dict['ObjectName']
            landmarkLine.Description=Dict['Description']
            landmarkLine.Line=self.Line
            landmarkLine.LandmarkType=landmarkType
            landmarkLine.CreateCommand=self
            landmarkLine.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            landmarkLine.SymbologyText=None
            landmarkLine.save()
            landmarkLine.SymbologyText=geography.GenerateLandmarkSymbologyTextValue(landmarkLine)           
            landmarkLine.save()
        elif(self.Name=='EditLandmarkLine'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None

            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                landmarkLine=djangoproject.models.geography.LandmarkLine.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                landmarkLine=djangoproject.models.geography.LandmarkLine.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            else:
                landmarkLine=None
            landmarkLine.Name=Dict['ObjectName']
            landmarkLine.Description=Dict['Description']
            landmarkLine.LandmarkType=landmarkType
            landmarkLine.Line=self.Line
            landmarkLine.CreateCommand=self
            landmarkLine.SymbologyText=geography.GenerateLandmarkSymbologyTextValue(landmarkLine)
            landmarkLine.save()
            ReturnObject=landmarkLine
        elif(self.Name=='DeleteLandmarkLine'):
            landmarkLine=geography.LandmarkLine.objects.filter(id=Dict['Objectid'])
            landmarkLine.delete()
            ReturnObject='Deleted a LandmarkLine'
        elif(self.Name=='CreateLandmarkPolygon'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None
            landmarkPolygon=geography.LandmarkPolygon()
            landmarkPolygon.Name=Dict['ObjectName']
            landmarkPolygon.Description=Dict['Description']
            landmarkPolygon.Polygon=self.Polygon
            landmarkPolygon.LandmarkType=landmarkType
            landmarkPolygon.CreateCommand=self
            landmarkPolygon.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            landmarkPolygon.SymbologyText = None
            landmarkPolygon.save()
            landmarkPolygon.SymbologyText = geography.GenerateLandmarkSymbologyTextValue(landmarkPolygon)
            landmarkPolygon.save()
            ReturnObject=landmarkPolygon
        elif(self.Name=='EditLandmarkPolygon'):
            if(Dict['LandmarkTypeid'] and Dict['LandmarkTypeid'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.filter(id=Dict['LandmarkTypeid'])[0]
            elif(Dict['LandmarkTypeIndexWhenReverseSorted'] <> None and Dict['LandmarkTypeIndexWhenReverseSorted'] <> -1):
                landmarkType=djangoproject.models.geography.LandmarkType.objects.all().order_by('-id')[Dict['LandmarkTypeIndexWhenReverseSorted']]
            else:
                landmarkType=None

            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                landmarkPolygon=djangoproject.models.geography.LandmarkPolygon.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                landmarkPolygon=djangoproject.models.geography.LandmarkPolygon.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            else:
                landmarkPolygon=None
            landmarkPolygon.Name=Dict['ObjectName']
            landmarkPolygon.Description=Dict['Description']
            landmarkPolygon.LandmarkType=landmarkType
            landmarkPolygon.Polygon=self.Polygon
            landmarkPolygon.CreateCommand=self
            landmarkPolygon.SymbologyText = geography.GenerateLandmarkSymbologyTextValue(landmarkPolygon)
            landmarkPolygon.save()
            ReturnObject=landmarkPolygon
        elif(self.Name=='DeleteLandmarkPolygon'):
            landmarkPolygon=geography.LandmarkPolygon.objects.filter(id=Dict['Objectid'])
            landmarkPolygon.delete()
            ReturnObject='Deleted a LandmarkPolygon'
        elif(self.Name=='CreateRoad'):
            road=geography.Road()
            road.Name=Dict['ObjectName']
            road.ShadowName=Dict['ObjectName']
            road.ShadowAlternateName=''
            Number=[]
            for i in road.Name:
                if(i.isdigit()):
                    Number.append(i)
            road.Number=''.join(Number)
            road.InterstateIndicator=Dict['InterstateIndicator']
            road.USHighwayIndicator=Dict['USHighwayIndicator']
            road.StateHighwayIndicator=Dict['StateHighwayIndicator']
            road.MainRoadIndicator=Dict['MainRoadIndicator']
            road.LeftFromAddress=Dict['LeftFromAddress']
            road.LeftToAddress=Dict['LeftToAddress']
            road.RightFromAddress=Dict['RightFromAddress']
            road.RightToAddress=Dict['RightToAddress']
            road.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            road.CreateCommand=self
            road.Line=self.Line
            road.save()
            road.CalculateSymbology()
            ReturnObject=road
        elif(self.Name=='EditRoad'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                road=geography.Road.objects.filter(id=Dict['Objectid'])[0]
            else:
                road=geography.Road.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            road.Name=Dict['ObjectName']
            road.ShadowName=Dict['ObjectName']
            road.ShadowAlternateName=''
            Number=[]
            for i in road.Name:
                if(i.isdigit()):
                    Number.append(i)
            road.Number=''.join(Number)
            road.InterstateIndicator=Dict['InterstateIndicator']
            road.USHighwayIndicator=Dict['USHighwayIndicator']
            road.StateHighwayIndicator=Dict['StateHighwayIndicator']
            road.MainRoadIndicator=Dict['MainRoadIndicator']
            road.LeftFromAddress=Dict['LeftFromAddress']
            road.LeftToAddress=Dict['LeftToAddress']
            road.RightFromAddress=Dict['RightFromAddress']
            road.RightToAddress=Dict['RightToAddress']
            road.CreateCommand=self
            road.Line=self.Line
            road.save()
            road.CalculateSymbology()
            ReturnObject=road
        elif(self.Name=='DeleteRoad'):
            road=geography.Road.objects.filter(id=Dict['Objectid'])
            road.delete()
            ReturnObject='Deleted a Road'
        elif(self.Name=='CreateCondition'):
            condition=djangoproject.models.maintenance.Condition()
            condition.PriorityImmediateIndicator=Dict['PriorityImmediateIndicator']
            condition.PriorityASAPIndicator=Dict['PriorityASAPIndicator']
            condition.PriorityRoutineIndicator=Dict['PriorityRoutineIndicator']
            condition.PriorityEverythingFixedMaintenanceOnlyIndicator=Dict['PriorityEverythingFixedMaintenanceOnlyIndicator']
            condition.PriorityEverythingOkInspectionOnlyIndicator=Dict['PriorityEverythingOkInspectionOnlyIndicator']
            condition.PriorityVegetationNeedsAttentionIndicator=Dict['PriorityVegetationNeedsAttentionIndicator']
            condition.PriorityOutdoorLightingConversionIndicator=Dict['PriorityOutdoorLightingConversionIndicator']
            condition.NeedsRetirementIndicator=Dict['NeedsRetirementIndicator']
            conditionDepartment=djangoproject.models.maintenance.ConditionDepartment.objects.filter(id=Dict['ConditionDepartmentid'])[0]
            condition.ConditionDepartment=conditionDepartment
            condition.PersonReporting=Dict['PersonReporting']
            condition.DateTimeReported=Dict['DateTimeReported']
            condition.ReceivedByOperationsIndicator=Dict['ReceivedByOperationsIndicator']
            condition.DateTimeReceivedByOperations=Dict['DateTimeReceivedByOperations']
            condition.StationIdentifier=Dict['StationIdentifier']
            if not self.TagNumber and not Dict['TagNumber']:
                Assemblies = djangoproject.models.compatibleunit.Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).filter(Station__id=Dict['StationIdentifier'])
                if Assemblies:
                    tag = Assemblies[0].TagNumber
                    condition.TagNumber = tag
            else:
                condition.TagNumber=self.TagNumber
            condition.Point=self.StartPoint
            condition.Description=Dict['Description']
            outdoorLightMapNumber=Dict['OutdoorLightMapNumber']
            condition.OutdoorLightMapNumber=outdoorLightMapNumber
            condition.OutdoorLightMeterNumber=Dict['OutdoorLightMeterNumber']
            condition.OutdoorLightMeterMapNumber=Dict['OutdoorLightMeterMapNumber']
            condition.OutdoorLightIdleIndicator=Dict['OutdoorLightIdleIndicator']
            condition.OutdoorLightCustomerOwnsPoleIndicator=Dict['OutdoorLightCustomerOwnsPoleIndicator']
            condition.OutdoorLightCustomerOwnsLightIndicator=Dict['OutdoorLightCustomerOwnsLightIndicator']
            if Dict['OutdoorLightRateid'] and not Dict['OutdoorLightRateid'] == -1:
                outdoorLightRate=djangoproject.models.maintenance.OutdoorLightRate.objects.filter(id=Dict['OutdoorLightRateid'])[0]
                condition.OutdoorLightRate=outdoorLightRate
            if Dict['OutdoorLightProblemCodeid'] == -1:
                condition.OutdoorLightProblemCode = None
            else:
                code = djangoproject.models.maintenance.OutdoorLightProblemCode.objects.get(id=Dict['OutdoorLightProblemCodeid'])
                condition.OutdoorLightProblemCode=code
            condition.OutdoorLightAdditionalBillingPoleCount=Dict['OutdoorLightAdditionalBillingPoleCount']
            condition.PoleConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['PoleConditionStatus'])[0]
            condition.GuyAnchorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['GuyAnchorConditionStatus'])[0]
            condition.InsulatorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['InsulatorConditionStatus'])[0]
            condition.ConductorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['ConductorConditionStatus'])[0]
            condition.RightOfWayConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['RightOfWayConditionStatus'])[0]
            condition.PadMountConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['PadMountConditionStatus'])[0]
            condition.VaultConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['VaultConditionStatus'])[0]
            condition.RiserCableConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['RiserCableConditionStatus'])[0]
            condition.WorkOrderNumber=Dict['WorkOrderNumber']
            condition.WorkRemarks=Dict['WorkRemarks']
            condition.WorkPerformedBy=Dict['WorkPerformedBy']
            condition.WorkHours=Dict['HoursWorkedQuantity']
            condition.WorkDate=Dict['WorkDate']
            condition.WorkCompletedIndicator=Dict['WorkCompletedIndicator']
            condition.WorkNotCompletedIndicator=Dict['WorkNotCompletedIndicator']
            condition.WorkNotCompletedDescription=Dict['WorkNotCompletedDescription']
            condition.WorkForeman=Dict['WorkForeman']
            condition.WorkForemanSignoffIndicator=Dict['WorkForemanSignoffIndicator']
            condition.WorkForemanSignoffDateTime=Dict['WorkForemanSignoffDateTime']
            condition.ReviewIndicator=Dict['ReviewIndicator']
            condition.ReviewAdditionalAttentionNeededIndicator=Dict['ReviewAdditionalAttentionNeededIndicator']
            condition.ReviewComments=Dict['ReviewComments']
            condition.ReviewUserName=Dict['ReviewUserName']
            condition.ReviewDateTime=Dict['ReviewDateTime']
            condition.ReviewAdditionalAttentionNeededIndicator=Dict['ReviewAdditionalAttentionNeededIndicator']
            condition.ReviewComments=Dict['ReviewComments']
            condition.ReviewUserName=Dict['ReviewUserName']
            condition.ReviewDateTime=Dict['ReviewDateTime']
            condition.DeletedIndicator=Dict['DeletedIndicator']
            condition.CreateDateTime=self.CommandCreateDateTime
            condition.CreateUserName=self.CommandUserName
            condition.LastModifyDateTime=self.CommandCreateDateTime
            condition.LastModifyUserName=self.CommandUserName
            archivedIndicator=Dict['ArchivedIndicator']
            if archivedIndicator:
                condition.ArchivedIndicator=archivedIndicator
                condition.ArchivedUserName=self.CommandUserName
                condition.ArchivedDateTime=self.CommandCreateDateTime
            condition.SymbologyYear=str(self.CommandCreateDateTime.year)

            #START CIRCUITNUMBER CHANGE
            StationCircuitNumbers=djangoproject.models.compatibleunit.Assembly.objects.filter(Station__id=Dict['StationIdentifier']).values_list('CircuitNumber', flat=True).distinct()
            CleanCircuitNumbersList=str(list(StationCircuitNumbers)).replace('[','').replace(']','')
            condition.CircuitNumbers=CleanCircuitNumbersList
            #END CIRCUITNUMBER CHANGE

            condition.OutdoorLightGISPhaseIndicator = Dict['OutdoorLightGISPhaseIndicator']
            condition.OutdoorLightSendBackToBillingPhaseIndicator = Dict['OutdoorLightSendBackToBillingPhaseIndicator']
            condition.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            condition.save()
            #outdoor light count requires update, but is not connected by ForeignKey
            try:
                MeterMapNumberNotEmpty=int(Dict['OutdoorLightMeterMapNumber'])
            except ValueError:
                MeterMapNumberNotEmpty=False
            if MeterMapNumberNotEmpty:
                OutdoorLightCount=djangoproject.models.maintenance.OutdoorLightConsumerOwnedLightCount.objects.filter(MeterMapNumber=Dict['OutdoorLightMeterMapNumber'])
                if OutdoorLightCount.count():
                    editLightCount=OutdoorLightCount[0]
                else:
                    editLightCount=djangoproject.models.maintenance.OutdoorLightConsumerOwnedLightCount()
                    editLightCount.CreateDateTime=self.CommandCreateDateTime
                    editLightCount.CreateUserName=self.CommandUserName
                editLightCount.MeterMapNumber=Dict['OutdoorLightMeterMapNumber']
                editLightCount.LightCount=Dict['OutdoorLightConsumerOwnedLightCount']
                editLightCount.LastModifyDateTime=self.CommandCreateDateTime
                editLightCount.LastModifyUserName=self.CommandUserName
                editLightCount.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
                editLightCount.save()
            ReturnObject=condition
        elif(self.Name=='EditCondition'):
            condition=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.maintenance.Condition, Dict)
            if not condition.ArchivedIndicator:
                condition.PriorityImmediateIndicator=Dict['PriorityImmediateIndicator']
                condition.PriorityASAPIndicator=Dict['PriorityASAPIndicator']
                condition.PriorityRoutineIndicator=Dict['PriorityRoutineIndicator']
                condition.PriorityEverythingFixedMaintenanceOnlyIndicator=Dict['PriorityEverythingFixedMaintenanceOnlyIndicator']
                condition.PriorityEverythingOkInspectionOnlyIndicator=Dict['PriorityEverythingOkInspectionOnlyIndicator']
                condition.PriorityVegetationNeedsAttentionIndicator=Dict['PriorityVegetationNeedsAttentionIndicator']
                condition.PriorityOutdoorLightingConversionIndicator=Dict['PriorityOutdoorLightingConversionIndicator']
                condition.NeedsRetirementIndicator=Dict['NeedsRetirementIndicator']
                conditionDepartment=djangoproject.models.maintenance.ConditionDepartment.objects.filter(id=Dict['ConditionDepartmentid'])[0]
                condition.ConditionDepartment=conditionDepartment                 
                condition.PersonReporting=Dict['PersonReporting']
                condition.DateTimeReported=Dict['DateTimeReported']
                condition.ReceivedByOperationsIndicator=Dict['ReceivedByOperationsIndicator']
                condition.DateTimeReceivedByOperations=Dict['DateTimeReceivedByOperations']
                condition.StationIdentifier=Dict['StationIdentifier']
                if not self.TagNumber and not Dict['TagNumber']:
                    Assemblies = djangoproject.models.compatibleunit.Assembly.objects.filter(CompatibleUnit__PoleIndicator=True).filter(Station__id=Dict['StationIdentifier'])
                    if Assemblies:
                        tag = Assemblies[0].TagNumber
                        condition.TagNumber = tag
                else:
                    condition.TagNumber=self.TagNumber
                condition.Point=self.StartPoint
                condition.Description=Dict['Description']
                outdoorLightMapNumber=Dict['OutdoorLightMapNumber']
                if not outdoorLightMapNumber:
                    StationLights=djangoproject.models.compatibleunit.Assembly.objects.filter(Station__id=Dict['StationIdentifier']).filter(CompatibleUnit__LightIndicator=True)
                    if not StationLights.count():
                        condition.OutdoorLightMapNumber=outdoorLightMapNumber
                    elif StationLights.count() == 1:
                        condition.OutdoorLightMapNumber=StationLights[0].MapNumber
                    else:
                        OutdoorLightMapNumbers = list(djangoproject.models.maintenance.Condition.objects.filter(PriorityOutdoorLightingConversionIndicator=True).exclude(
                                                DeletedIndicator=True).values_list('OutdoorLightMapNumber', flat=True))
                        UnclaimedLights = [i for i in StationLights if not i.MapNumber in OutdoorLightMapNumbers]
                        if UnclaimedLights:
                            condition.OutdoorLightMapNumber = UnclaimedLights[0].MapNumber
                        else:
                            condition.OutdoorLightMapNumber = 'Contact Technology for New MapNumber'
                else:
                    condition.OutdoorLightMapNumber=outdoorLightMapNumber
                condition.OutdoorLightMeterNumber=Dict['OutdoorLightMeterNumber']
                condition.OutdoorLightMeterMapNumber=Dict['OutdoorLightMeterMapNumber']
                condition.OutdoorLightIdleIndicator=Dict['OutdoorLightIdleIndicator']
                condition.OutdoorLightCustomerOwnsPoleIndicator=Dict['OutdoorLightCustomerOwnsPoleIndicator']
                condition.OutdoorLightCustomerOwnsLightIndicator=Dict['OutdoorLightCustomerOwnsLightIndicator']
                if Dict['OutdoorLightRateid'] == -1:
                    condition.OutdoorLightRate=None
                else:
                    outdoorLightRate=djangoproject.models.maintenance.OutdoorLightRate.objects.filter(id=Dict['OutdoorLightRateid'])[0]
                    condition.OutdoorLightRate=outdoorLightRate
                if Dict['OutdoorLightProblemCodeid'] == -1:
                    condition.OutdoorLightProblemCode = None
                else:
                    code = djangoproject.models.maintenance.OutdoorLightProblemCode.objects.get(id=Dict['OutdoorLightProblemCodeid'])
                    condition.OutdoorLightProblemCode=code
                condition.OutdoorLightAdditionalBillingPoleCount=Dict['OutdoorLightAdditionalBillingPoleCount']
                condition.PoleConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['PoleConditionStatus'])[0]
                condition.GuyAnchorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['GuyAnchorConditionStatus'])[0]
                condition.InsulatorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['InsulatorConditionStatus'])[0]
                condition.ConductorConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['ConductorConditionStatus'])[0]
                condition.RightOfWayConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['RightOfWayConditionStatus'])[0]
                condition.PadMountConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['PadMountConditionStatus'])[0]
                condition.VaultConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['VaultConditionStatus'])[0]
                condition.RiserCableConditionStatus=djangoproject.models.maintenance.ConditionStatus.objects.filter(id=Dict['RiserCableConditionStatus'])[0]
                condition.WorkOrderNumber=Dict['WorkOrderNumber']
                condition.WorkRemarks=Dict['WorkRemarks']
                condition.WorkPerformedBy=Dict['WorkPerformedBy']
                condition.WorkHours=Dict['HoursWorkedQuantity']
                condition.WorkDate=Dict['WorkDate']
                condition.WorkCompletedIndicator=Dict['WorkCompletedIndicator']
                condition.WorkNotCompletedIndicator=Dict['WorkNotCompletedIndicator']
                condition.WorkNotCompletedDescription=Dict['WorkNotCompletedDescription']
                condition.WorkForeman=Dict['WorkForeman']
                condition.WorkForemanSignoffIndicator=Dict['WorkForemanSignoffIndicator']
                condition.WorkForemanSignoffDateTime=Dict['WorkForemanSignoffDateTime']
                condition.ReviewIndicator=Dict['ReviewIndicator']
                condition.ReviewAdditionalAttentionNeededIndicator=Dict['ReviewAdditionalAttentionNeededIndicator']
                condition.ReviewComments=Dict['ReviewComments']
                condition.ReviewUserName=Dict['ReviewUserName']
                condition.ReviewDateTime=Dict['ReviewDateTime']
                condition.DeletedIndicator=Dict['DeletedIndicator']
                condition.LastModifyUserName=self.CommandUserName
                condition.LastModifyDateTime=self.CommandCreateDateTime
                archivedIndicator=Dict['ArchivedIndicator']
                if archivedIndicator:
                    condition.ArchivedIndicator=archivedIndicator
                    condition.ArchivedUserName=self.CommandUserName
                    condition.ArchivedDateTime=self.CommandCreateDateTime


                StationCircuitNumbers=djangoproject.models.compatibleunit.Assembly.objects.filter(Station__id=Dict['StationIdentifier']).values_list('CircuitNumber', flat=True).distinct()
                CleanCircuitNumbersList=str(list(StationCircuitNumbers)).replace('[','').replace(']','')
                condition.CircuitNumbers=CleanCircuitNumbersList


                condition.OutdoorLightGISPhaseIndicator=Dict['OutdoorLightGISPhaseIndicator']
                condition.OutdoorLightSendBackToBillingPhaseIndicator=Dict['OutdoorLightSendBackToBillingPhaseIndicator']
                condition.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
                condition.save()
                #outdoor light count requires update, but is not connected by ForeignKey
                try:
                    MeterMapNumberNotEmpty=int(Dict['OutdoorLightMeterMapNumber'])
                except ValueError:
                    MeterMapNumberNotEmpty=False
                if MeterMapNumberNotEmpty and not Dict['OutdoorLightConsumerOwnedLightCount'] == 'OverrideIgnore':
                    OutdoorLightCount=djangoproject.models.maintenance.OutdoorLightConsumerOwnedLightCount.objects.filter(MeterMapNumber=Dict['OutdoorLightMeterMapNumber'])
                    if OutdoorLightCount.count():
                        editLightCount=OutdoorLightCount[0]
                    else:
                        editLightCount=djangoproject.models.maintenance.OutdoorLightConsumerOwnedLightCount()
                        editLightCount.CreateDateTime=self.CommandCreateDateTime
                        editLightCount.CreateUserName=self.CommandUserName
                    editLightCount.MeterMapNumber=Dict['OutdoorLightMeterMapNumber']
                    editLightCount.LightCount=Dict['OutdoorLightConsumerOwnedLightCount']
                    editLightCount.LastModifyDateTime=self.CommandCreateDateTime
                    editLightCount.LastModifyUserName=self.CommandUserName
                    editLightCount.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
                    editLightCount.save()
        elif(self.Name=='CreateConditionMemberDescriptionHistory'):
            new=djangoproject.models.maintenance.ConditionMemberDescriptionHistory()
            new.id = djangoproject.models.maintenance.ConditionMemberDescriptionHistory.objects.all().order_by('-id')[0].id + 1
            new.Condition=GetObjectFromidandReverseSortedIndex('Condition', djangoproject.models.maintenance.Condition, Dict)
            new.Description=Dict['Description']
            new.CreateDateTime=self.CommandCreateDateTime
            new.CreateUserName=self.CommandUserName
            new.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            new.save()
        elif(self.Name=='EditConditionMemberDescriptionHistory'):
            history=djangoproject.models.maintenance.ConditionMemberDescriptionHistory.objects.filter(id=Dict['Conditionid'])[0]
            history.Condition=GetObjectFromidandReverseSortedIndex('Condition', djangoproject.models.maintenance.Condition, Dict)
            history.Description=Dict['Description']
            history.CreateDateTime=self.CommandCreateDateTime
            history.CreateUserName=self.CommandUserName
            history.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            history.save()
        elif(self.Name=='CreateConditionAssignment'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                condition=djangoproject.models.maintenance.Condition.objects.filter(id=Dict['Objectid'])[0]
            else:
                condition=djangoproject.models.maintenance.Condition.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            conditionAssignment=djangoproject.models.maintenance.ConditionAssignment()
            conditionAssignment.Name=Dict['ObjectName']
            conditionAssignment.Description=Dict['Description']
            conditionAssignment.CreateDateTime=self.CommandCreateDateTime
            conditionAssignment.CreateUserName=self.CommandUserName
            conditionAssignment.Condition=condition
            conditionAssignment.save()
            ReturnObject=conditionAssignment
        elif(self.Name=='CreateSubstation'):
            if(Dict['Assemblyid'] and Dict['Assemblyid'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.filter(id=Dict['Assemblyid'])[0]
            elif(Dict['AssemblyIndexWhenReverseSorted'] <> None and Dict['AssemblyIndexWhenReverseSorted'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.all().order_by('-id')[Dict['AssemblyIndexWhenReverseSorted']]
            else:
                assembly=None
            substation=djangoproject.models.substationmodel.Substation()
            substation.Name=Dict['ObjectName']
            substation.Assembly=assembly
            substation.Description=Dict['Description']
            substation.ActiveIndicator=Dict['ActiveIndicator']
            
            substation.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substation.save()
            ReturnObject=substation
        elif(self.Name=='EditSubstation'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substation=djangoproject.models.substationmodel.Substation.objects.filter(id=Dict['Objectid'])[0]
            else:
                substation=djangoproject.models.substationmodel.Substation.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            substation.Name=Dict['ObjectName']
            substation.Description=Dict['Description']
            if(Dict['Assemblyid'] and Dict['Assemblyid'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.filter(id=Dict['Assemblyid'])[0]
            elif(Dict['AssemblyIndexWhenReverseSorted'] <> None and Dict['AssemblyIndexWhenReverseSorted'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.all().order_by('-id')[Dict['AssemblyIndexWhenReverseSorted']]
            else:
                assembly=None
            substation.Assembly=assembly
            substation.ActiveIndicator=Dict['ActiveIndicator']
            substation.save()
            ReturnObject=substation
        elif(self.Name=='DeleteSubstation'):
            substation=Substation.objects.filter(id=Dict['Objectid'])[0]
            if(not SubstationInspection.objects.filter(Substation=substation) and not SubstationEquipment.objects.filter(Substation=substation)):
                substation.delete()
                ReturnObject='Deleted'
            else:
                ReturnObject='Did Not Delete Substation, related SubstationInspections or SubstationEquipment exist.'
        elif(self.Name=='CreateSubstationEquipment'):
            substationEquipment=djangoproject.models.substationmodel.SubstationEquipment()
            substationEquipment.Name=Dict['SubstationEquipmentName']
            substationEquipment.InventoryNumber=Dict['InventoryNumber']
            substationEquipment.CatalogNumber=Dict['CatalogNumber']
            substationEquipment.SubstationEquipmentModelType=GetObjectFromidandReverseSortedIndex('SubstationEquipmentModelType', djangoproject.models.substationmodel.SubstationEquipmentModelType, Dict)
            substationEquipment.RatedTransmissionVoltage1=GetObjectFromidandReverseSortedIndex('RatedTransmissionVoltage1', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedTransmissionVoltage2=GetObjectFromidandReverseSortedIndex('RatedTransmissionVoltage2', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedDistributionVoltage1=GetObjectFromidandReverseSortedIndex('RatedDistributionVoltage1', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedDistributionVoltage2=GetObjectFromidandReverseSortedIndex('RatedDistributionVoltage2', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.OperatorControlVoltage=GetObjectFromidandReverseSortedIndex('OperatorControlVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.CurrentTransmissionVoltage=GetObjectFromidandReverseSortedIndex('CurrentTransmissionVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.CurrentDistributionVoltage=GetObjectFromidandReverseSortedIndex('CurrentDistributionVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.KVARating=Dict['KVARating']
            substationEquipment.MVARating=Dict['MVARating']
            if(Dict['Manufacturerid'] and Dict['Manufacturerid'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['Manufacturerid'])[0]
            elif(Dict['ManufacturerIndexWhenReverseSorted'] <> None and Dict['ManufacturerIndexWhenReverseSorted'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['ManufacturerIndexWhenReverseSorted']]
            else:
                manufacturer=None
            substationEquipment.Manufacturer=manufacturer
            substationEquipment.DateOfManufacture=Dict['DateOfManufacture']
            substationEquipment.Impedance=Dict['Impedance']
            substationEquipment.OilCapacityGallon=Dict['OilCapacityGallon']
            substationEquipment.WeightPound=Dict['WeightPound']
            if(Dict['BatteryChargerManufacturerid'] and Dict['BatteryChargerManufacturerid'] <> -1):
                batteryChargerManufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['BatteryChargerManufacturerid'])[0]
            elif(Dict['BatteryChargerManufacturerIndexWhenReverseSorted'] <> None and Dict['BatteryChargerManufacturerIndexWhenReverseSorted'] <> -1):
                batteryChargerManufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['BatteryChargerManufacturerIndexWhenReverseSorted']]
            else:
                batteryChargerManufacturer=None
            substationEquipment.BatteryChargerManufacturer=batteryChargerManufacturer
            substationEquipment.BatteryChargerDateOfManufacture=Dict['BatteryChargerDateOfManufacture']
            if(Dict['BatteryChargerInputVoltageid'] and Dict['BatteryChargerInputVoltageid'] <> -1):
                batteryChargerInputVoltage=djangoproject.models.compatibleunit.Voltage.objects.filter(id=Dict['BatteryChargerInputVoltageid'])[0]
            elif(Dict['BatteryChargerInputVoltageIndexWhenReverseSorted'] <> None and Dict['BatteryChargerInputVoltageIndexWhenReverseSorted'] <> -1):
                batteryChargerInputVoltage=djangoproject.models.compatibleunit.Voltage.objects.all().order_by('-id')[Dict['BatteryChargerInputVoltageIndexWhenReverseSorted']]
            else:
                batteryChargerInputVoltage=None
            substationEquipment.BatteryChargerInputVoltage=batteryChargerInputVoltage
            if(Dict['BatteryChargerOutputVoltageid'] and Dict['BatteryChargerOutputVoltageid'] <> -1):
                batteryChargerOutputVoltage=djangoproject.models.compatibleunit.Voltage.objects.filter(id=Dict['BatteryChargerOutputVoltageid'])[0]
            elif(Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted'] <> None and Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted'] <> -1):
                batteryChargerOutputVoltage=djangoproject.models.compatibleunit.Voltage.objects.all().order_by('-id')[Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted']]
            else:
                batteryChargerOutputVoltage=None
            substationEquipment.BatteryChargerOutputVoltage=batteryChargerOutputVoltage
            substationEquipment.BatteryChargerACAmps=Dict['BatteryChargerACAmps']
            substationEquipment.BatteryChargerDCAmps=Dict['BatteryChargerDCAmps']
            substationEquipment.BatteryChargerNumberOfCells=Dict['BatteryChargerNumberOfCells']
            substationEquipment.BatteryChargerTypeOfCells=Dict['BatteryChargerTypeOfCells']
            substationEquipment.BatteryBankBatteryVoltage=Dict['BatteryBankBatteryVoltage']
            substationEquipment.BatteryBankBatteryAmpHours=Dict['BatteryBankBatteryAmpHours']
            substationEquipment.BatteryBankBatteryReserveCapacity=Dict['BatteryBankBatteryReserveCapacity']
            substationEquipment.BatteryBankBatteryModelNumber=Dict['BatteryBankBatteryModelNumber']
            if(Dict['SubstationEquipmentOverCurrentRelayTypeid'] and Dict['SubstationEquipmentOverCurrentRelayTypeid'] <> -1):
                substationEquipmentOverCurrentRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentOverCurrentRelayTypeVoltageid'])[0]
            elif(Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentOverCurrentRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentOverCurrentRelayType=None
            substationEquipment.SubstationEquipmentOverCurrentRelayType=substationEquipmentOverCurrentRelayType
            if(Dict['SubstationEquipmentDifferentialRelayTypeid'] and Dict['SubstationEquipmentDifferentialRelayTypeid'] <> -1):
                substationEquipmentDifferentialRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentDifferentialRelayTypeVoltageid'])[0]
            elif(Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentDifferentialRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentDifferentialRelayType=None
            substationEquipment.SubstationEquipmentDifferentialRelayType=substationEquipmentDifferentialRelayType
            if(Dict['SubstationEquipmentRegulatorControllerTypeid'] and Dict['SubstationEquipmentRegulatorControllerTypeid'] <> -1):
                substationEquipmentRegulatorControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentRegulatorControllerTypeid'])[0]
            elif(Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentRegulatorControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentRegulatorControllerType=None
            substationEquipment.SubstationEquipmentRegulatorControllerType=substationEquipmentRegulatorControllerType
            substationEquipment.RegulatorControllerSerialNumber=Dict['RegulatorControllerSerialNumber']
            if(Dict['RecloserControllerTypeid'] and Dict['RecloserControllerTypeid'] <> -1):
                recloserControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['RecloserControllerTypeid'])[0]
            elif(Dict['RecloserControllerTypeIndexWhenReverseSorted'] <> None and Dict['RecloserControllerTypeIndexWhenReverseSorted'] <> -1):
                recloserControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['RecloserControllerTypeIndexWhenReverseSorted']]
            else:
                recloserControllerType=None
            substationEquipment.RecloserControllerType=recloserControllerType
            substationEquipment.SerialNumber=Dict['SerialNumber']
            substationEquipment.Description=Dict['Description']
            if(Dict['Assemblyid'] and Dict['Assemblyid'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.filter(id=Dict['Assemblyid'])[0]
            elif(Dict['AssemblyIndexWhenReverseSorted'] <> None and Dict['AssemblyIndexWhenReverseSorted'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.all().order_by('-id')[Dict['AssemblyIndexWhenReverseSorted']]
            else:
                assembly=None
            substationEquipment.Assembly=assembly
            substationEquipment.ActiveIndicator=Dict['ActiveIndicator']
            if(Dict['SubstationEquipmentTemplateid'] and Dict['SubstationEquipmentTemplateid'] <> -1):
                substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate.objects.filter(id=Dict['SubstationEquipmentTemplateid'])[0]
            elif(Dict['SubstationEquipmentTemplateIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentTemplateIndexWhenReverseSorted'] <> -1):
                substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate.objects.all().order_by('-id')[Dict['SubstationEquipmentTemplateIndexWhenReverseSorted']]
            else:
                substationEquipmentTemplate=None
            substationEquipment.SubstationEquipmentTemplate=substationEquipmentTemplate
            substationEquipment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipment.save()
            ReturnObject=substationEquipment
        elif(self.Name=='EditSubstationEquipment'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.filter(id=Dict['Objectid'])[0]
            else:
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            substationEquipment.Name=Dict['SubstationEquipmentName']
            substationEquipment.InventoryNumber=Dict['InventoryNumber']
            substationEquipment.CatalogNumber=Dict['CatalogNumber']
            substationEquipment.SubstationEquipmentModelType=GetObjectFromidandReverseSortedIndex('SubstationEquipmentModelType', djangoproject.models.substationmodel.SubstationEquipmentModelType, Dict)
            substationEquipment.RatedTransmissionVoltage1=GetObjectFromidandReverseSortedIndex('RatedTransmissionVoltage1', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedTransmissionVoltage2=GetObjectFromidandReverseSortedIndex('RatedTransmissionVoltage2', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedDistributionVoltage1=GetObjectFromidandReverseSortedIndex('RatedDistributionVoltage1', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.RatedDistributionVoltage2=GetObjectFromidandReverseSortedIndex('RatedDistributionVoltage2', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.OperatorControlVoltage=GetObjectFromidandReverseSortedIndex('OperatorControlVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.CurrentTransmissionVoltage=GetObjectFromidandReverseSortedIndex('CurrentTransmissionVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.CurrentDistributionVoltage=GetObjectFromidandReverseSortedIndex('CurrentDistributionVoltage', djangoproject.models.compatibleunit.Voltage, Dict)
            substationEquipment.KVARating=Dict['KVARating']
            substationEquipment.MVARating=Dict['MVARating']
            if(Dict['Manufacturerid'] and Dict['Manufacturerid'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['Manufacturerid'])[0]
            elif(Dict['ManufacturerIndexWhenReverseSorted'] <> None and Dict['ManufacturerIndexWhenReverseSorted'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['ManufacturerIndexWhenReverseSorted']]
            else:
                manufacturer=None
            substationEquipment.Manufacturer=manufacturer
            substationEquipment.DateOfManufacture=Dict['DateOfManufacture']
            substationEquipment.Impedance=Dict['Impedance']
            substationEquipment.OilCapacityGallon=Dict['OilCapacityGallon']
            substationEquipment.WeightPound=Dict['WeightPound']
            if(Dict['BatteryChargerManufacturerid'] and Dict['BatteryChargerManufacturerid'] <> -1):
                batteryChargerManufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['BatteryChargerManufacturerid'])[0]
            elif(Dict['BatteryChargerManufacturerIndexWhenReverseSorted'] <> None and Dict['BatteryChargerManufacturerIndexWhenReverseSorted'] <> -1):
                batteryChargerManufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['BatteryChargerManufacturerIndexWhenReverseSorted']]
            else:
                batteryChargerManufacturer=None
            substationEquipment.BatteryChargerManufacturer=batteryChargerManufacturer
            substationEquipment.BatteryChargerDateOfManufacture=Dict['BatteryChargerDateOfManufacture']
            if(Dict['BatteryChargerInputVoltageid'] and Dict['BatteryChargerInputVoltageid'] <> -1):
                batteryChargerInputVoltage=djangoproject.models.compatibleunit.Voltage.objects.filter(id=Dict['BatteryChargerInputVoltageid'])[0]
            elif(Dict['BatteryChargerInputVoltageIndexWhenReverseSorted'] <> None and Dict['BatteryChargerInputVoltageIndexWhenReverseSorted'] <> -1):
                batteryChargerInputVoltage=djangoproject.models.compatibleunit.Voltage.objects.all().order_by('-id')[Dict['BatteryChargerInputVoltageIndexWhenReverseSorted']]
            else:
                batteryChargerInputVoltage=None
            substationEquipment.BatteryChargerInputVoltage=batteryChargerInputVoltage
            if(Dict['BatteryChargerOutputVoltageid'] and Dict['BatteryChargerOutputVoltageid'] <> -1):
                batteryChargerOutputVoltage=djangoproject.models.compatibleunit.Voltage.objects.filter(id=Dict['BatteryChargerOutputVoltageid'])[0]
            elif(Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted'] <> None and Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted'] <> -1):
                batteryChargerOutputVoltage=djangoproject.models.compatibleunit.Voltage.objects.all().order_by('-id')[Dict['BatteryChargerOutputVoltageIndexWhenReverseSorted']]
            else:
                batteryChargerOutputVoltage=None
            substationEquipment.BatteryChargerOutputVoltage=batteryChargerOutputVoltage
            substationEquipment.BatteryChargerACAmps=Dict['BatteryChargerACAmps']
            substationEquipment.BatteryChargerDCAmps=Dict['BatteryChargerDCAmps']
            substationEquipment.BatteryChargerNumberOfCells=Dict['BatteryChargerNumberOfCells']
            substationEquipment.BatteryChargerTypeOfCells=Dict['BatteryChargerTypeOfCells']
            substationEquipment.BatteryBankBatteryVoltage=Dict['BatteryBankBatteryVoltage']
            substationEquipment.BatteryBankBatteryAmpHours=Dict['BatteryBankBatteryAmpHours']
            substationEquipment.BatteryBankBatteryReserveCapacity=Dict['BatteryBankBatteryReserveCapacity']
            substationEquipment.BatteryBankBatteryModelNumber=Dict['BatteryBankBatteryModelNumber']
            if(Dict['SubstationEquipmentOverCurrentRelayTypeid'] and Dict['SubstationEquipmentOverCurrentRelayTypeid'] <> -1):
                substationEquipmentOverCurrentRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentOverCurrentRelayTypeVoltageid'])[0]
            elif(Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentOverCurrentRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentOverCurrentRelayTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentOverCurrentRelayType=None
            substationEquipment.SubstationEquipmentOverCurrentRelayType=substationEquipmentOverCurrentRelayType
            if(Dict['SubstationEquipmentDifferentialRelayTypeid'] and Dict['SubstationEquipmentDifferentialRelayTypeid'] <> -1):
                substationEquipmentDifferentialRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentDifferentialRelayTypeVoltageid'])[0]
            elif(Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentDifferentialRelayType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentDifferentialRelayTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentDifferentialRelayType=None
            substationEquipment.SubstationEquipmentDifferentialRelayType=substationEquipmentDifferentialRelayType
            if(Dict['SubstationEquipmentRegulatorControllerTypeid'] and Dict['SubstationEquipmentRegulatorControllerTypeid'] <> -1):
                substationEquipmentRegulatorControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['SubstationEquipmentRegulatorControllerTypeid'])[0]
            elif(Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted'] <> -1):
                substationEquipmentRegulatorControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['SubstationEquipmentRegulatorControllerTypeIndexWhenReverseSorted']]
            else:
                substationEquipmentRegulatorControllerType=None
            substationEquipment.SubstationEquipmentRegulatorControllerType=substationEquipmentRegulatorControllerType
            substationEquipment.RegulatorControllerSerialNumber=Dict['RegulatorControllerSerialNumber']
            if(Dict['RecloserControllerTypeid'] and Dict['RecloserControllerTypeid'] <> -1):
                recloserControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['RecloserControllerTypeid'])[0]
            elif(Dict['RecloserControllerTypeIndexWhenReverseSorted'] <> None and Dict['RecloserControllerTypeIndexWhenReverseSorted'] <> -1):
                recloserControllerType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['RecloserControllerTypeIndexWhenReverseSorted']]
            else:
                recloserControllerType=None
            substationEquipment.RecloserControllerType=recloserControllerType
            substationEquipment.SerialNumber=Dict['SerialNumber']
            substationEquipment.Description=Dict['Description']
            if(Dict['Assemblyid'] and Dict['Assemblyid'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.filter(id=Dict['Assemblyid'])[0]
            elif(Dict['AssemblyIndexWhenReverseSorted'] <> None and Dict['AssemblyIndexWhenReverseSorted'] <> -1):
                assembly=djangoproject.models.compatibleunit.Assembly.objects.all().order_by('-id')[Dict['AssemblyIndexWhenReverseSorted']]
            else:
                assembly=None
            substationEquipment.Assembly=assembly
            substationEquipment.ActiveIndicator=Dict['ActiveIndicator']
            if(Dict['SubstationEquipmentTemplateid'] and Dict['SubstationEquipmentTemplateid'] <> -1):
                substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate.objects.filter(id=Dict['SubstationEquipmentTemplateid'])[0]
            elif(Dict['SubstationEquipmentTemplateIndexWhenReverseSorted'] <> None and Dict['SubstationEquipmentTemplateIndexWhenReverseSorted'] <> -1):
                substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate.objects.all().order_by('-id')[Dict['SubstationEquipmentTemplateIndexWhenReverseSorted']]
            else:
                substationEquipmentTemplate=None
            substationEquipment.SubstationEquipmentTemplate=substationEquipmentTemplate
            substationEquipment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipment.save()
            ReturnObject=substationEquipment
        elif(self.Name=='DeleteSubstationEquipment'):
            substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.filter(id=Dict['Objectid'])[0]
            if(not SubstationEquipmentInspection.objects.filter(SubstationEquipment=substationEquipment)):
                substationEquipment.delete()
                ReturnObject='Deleted Substation Equipment'
            else:
                ReturnObject='Did Not Delete SubstationEquipment, related SubstationEquipmentInspections exist.'
        elif(self.Name=='CreateSubstationEquipmentInspection'):
            substationEquipmentInspection=djangoproject.models.substationmodel.SubstationEquipmentInspection()
            substationEquipmentInspection.CreateDateTime=Dict['CreateDateTime']
            substationEquipmentInspection.LastModifyDateTime=Dict['CreateDateTime']
            substationEquipmentInspection.CreateUserName=Dict['CreateUserName']
            substationEquipmentInspection.LastModifyUserName=Dict['CreateUserName']
            substationEquipmentInspection.Description=Dict['Description']
            substationEquipmentInspection.BatteryTest=GetObjectFromidandReverseSortedIndex('BatteryTest', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.BatteryCharge=Dict['BatteryCharge']
            substationEquipmentInspection.BatteryVisual=GetObjectFromidandReverseSortedIndex('BatteryVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.BatteryVoltageTest=Dict['BatteryVoltageTest']
            substationEquipmentInspection.BatteryVoltageNormal=Dict['BatteryVoltageNormal']
            substationEquipmentInspection.Ground=GetObjectFromidandReverseSortedIndex('Ground', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.Visual=GetObjectFromidandReverseSortedIndex('Visual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.MeterKWH=Dict['MeterKWH']
            substationEquipmentInspection.MeterKW=Dict['MeterKW']
            substationEquipmentInspection.MeterVisual=GetObjectFromidandReverseSortedIndex('MeterVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.OperationCounter=Dict['OperationCounter']
            substationEquipmentInspection.RecloserAmperageA=Dict['RecloserAmperageA']
            substationEquipmentInspection.RecloserAmperageB=Dict['RecloserAmperageB']
            substationEquipmentInspection.RecloserAmperageC=Dict['RecloserAmperageC']
            substationEquipmentInspection.RecloserAmperageGround=Dict['RecloserAmperageGround']
            substationEquipmentInspection.RecloserMaxDemandA=Dict['RecloserMaxDemandA']
            substationEquipmentInspection.RecloserMaxDemandB=Dict['RecloserMaxDemandB']
            substationEquipmentInspection.RecloserMaxDemandC=Dict['RecloserMaxDemandC']
            substationEquipmentInspection.RecloserMaxDemandGround=Dict['RecloserMaxDemandGround']
            substationEquipmentInspection.RecloserOperationSummaryA=Dict['RecloserOperationSummaryA']
            substationEquipmentInspection.RecloserOperationSummaryB=Dict['RecloserOperationSummaryB']
            substationEquipmentInspection.RecloserOperationSummaryC=Dict['RecloserOperationSummaryC']
            substationEquipmentInspection.RecloserTargetA=Dict['RecloserTargetA']
            substationEquipmentInspection.RecloserTargetB=Dict['RecloserTargetB']
            substationEquipmentInspection.RecloserTargetC=Dict['RecloserTargetC']
            substationEquipmentInspection.RecloserTargetGround=Dict['RecloserTargetGround']
            substationEquipmentInspection.RegulatorDragHandPositionMinimum=Dict['RegulatorDragHandPositionMinimum']
            substationEquipmentInspection.RegulatorDragHandPositionCurrent=Dict['RegulatorDragHandPositionCurrent']
            substationEquipmentInspection.RegulatorDragHandPositionMaximum=Dict['RegulatorDragHandPositionMaximum']
            substationEquipmentInspection.RegulatorVoltHigh=Dict['RegulatorVoltHigh']
            substationEquipmentInspection.RegulatorVoltLow=Dict['RegulatorVoltLow']
            substationEquipmentInspection.RegulatorVoltCurrent=Dict['RegulatorVoltCurrent']
            substationEquipmentInspection.RegulatorMaxAmp=Dict['RegulatorMaxAmp']
            substationEquipmentInspection.SurgeProtectorVisual=GetObjectFromidandReverseSortedIndex('SurgeProtectorVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilLeak=GetObjectFromidandReverseSortedIndex('TransformerOilLeak', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilLevel=GetObjectFromidandReverseSortedIndex('TransformerOilLevel', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilTemperatureCurrent=Dict['TransformerOilTemperatureCurrent']
            substationEquipmentInspection.TransformerOilTemperatureMaximum=Dict['TransformerOilTemperatureMaximum']
            substationEquipmentInspection.TransformerNitrogenPressure=Dict['TransformerNitrogenPressure']
            substationEquipmentInspection.TransformerOilVisual=GetObjectFromidandReverseSortedIndex('TransformerOilVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerWindingTemperatureCurrent=Dict['TransformerWindingTemperatureCurrent']
            substationEquipmentInspection.TransformerWindingTemperatureMaximum=Dict['TransformerWindingTemperatureMaximum']
            substationEquipmentInspection.SubstationEquipment=GetObjectFromidandReverseSortedIndex('SubstationEquipment', djangoproject.models.substationmodel.SubstationEquipment, Dict)
            substationEquipmentInspection.MechanismCharge=GetObjectFromidandReverseSortedIndex('MechanismCharge', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.FanWorkingVisual=GetObjectFromidandReverseSortedIndex('FanWorkingVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.DemandAmpA=Dict['DemandAmpA']
            substationEquipmentInspection.DemandAmpB=Dict['DemandAmpB']
            substationEquipmentInspection.DemandAmpC=Dict['DemandAmpC']
            substationEquipmentInspection.OverCurrentTrip=Dict['OverCurrentTrip']
            substationEquipmentInspection.BreakerCounter=Dict['BreakerCounter']
            substationEquipmentInspection.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentInspection.save()
            ReturnObject=substationEquipmentInspection
        elif(self.Name=='EditSubstationEquipmentInspection'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substationEquipmentInspection=djangoproject.models.substationmodel.SubstationEquipmentInspection.objects.filter(id=Dict['Objectid'])[0]
            else:
                substationEquipmentInspection=djangoproject.models.substationmodel.SubstationEquipmentInspection.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            substationEquipmentInspection.LastModifyDateTime=Dict['LastModifyDateTime']
            substationEquipmentInspection.LastModifyUserName=Dict['LastModifyUserName']
            substationEquipmentInspection.Description=Dict['Description']
            substationEquipmentInspection.BatteryTest=GetObjectFromidandReverseSortedIndex('BatteryTest', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.BatteryCharge=Dict['BatteryCharge']
            substationEquipmentInspection.BatteryVisual=GetObjectFromidandReverseSortedIndex('BatteryVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.BatteryVoltageTest=Dict['BatteryVoltageTest']
            substationEquipmentInspection.BatteryVoltageNormal=Dict['BatteryVoltageNormal']
            substationEquipmentInspection.Ground=GetObjectFromidandReverseSortedIndex('Ground', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.Visual=GetObjectFromidandReverseSortedIndex('Visual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.MeterKWH=Dict['MeterKWH']
            substationEquipmentInspection.MeterKW=Dict['MeterKW']
            substationEquipmentInspection.OperationCounter=Dict['OperationCounter']
            substationEquipmentInspection.MeterVisual=GetObjectFromidandReverseSortedIndex('MeterVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.RecloserAmperageA=Dict['RecloserAmperageA']
            substationEquipmentInspection.RecloserAmperageB=Dict['RecloserAmperageB']
            substationEquipmentInspection.RecloserAmperageC=Dict['RecloserAmperageC']
            substationEquipmentInspection.RecloserAmperageGround=Dict['RecloserAmperageGround']
            substationEquipmentInspection.RecloserMaxDemandA=Dict['RecloserMaxDemandA']
            substationEquipmentInspection.RecloserMaxDemandB=Dict['RecloserMaxDemandB']
            substationEquipmentInspection.RecloserMaxDemandC=Dict['RecloserMaxDemandC']
            substationEquipmentInspection.RecloserMaxDemandGround=Dict['RecloserMaxDemandGround']
            substationEquipmentInspection.RecloserOperationSummaryA=Dict['RecloserOperationSummaryA']
            substationEquipmentInspection.RecloserOperationSummaryB=Dict['RecloserOperationSummaryB']
            substationEquipmentInspection.RecloserOperationSummaryC=Dict['RecloserOperationSummaryC']
            substationEquipmentInspection.RecloserTargetA=Dict['RecloserTargetA']
            substationEquipmentInspection.RecloserTargetB=Dict['RecloserTargetB']
            substationEquipmentInspection.RecloserTargetC=Dict['RecloserTargetC']
            substationEquipmentInspection.RecloserTargetGround=Dict['RecloserTargetGround']
            substationEquipmentInspection.RegulatorDragHandPositionMinimum=Dict['RegulatorDragHandPositionMinimum']
            substationEquipmentInspection.RegulatorDragHandPositionCurrent=Dict['RegulatorDragHandPositionCurrent']
            substationEquipmentInspection.RegulatorDragHandPositionMaximum=Dict['RegulatorDragHandPositionMaximum']
            substationEquipmentInspection.RegulatorVoltHigh=Dict['RegulatorVoltHigh']
            substationEquipmentInspection.RegulatorVoltLow=Dict['RegulatorVoltLow']
            substationEquipmentInspection.RegulatorVoltCurrent=Dict['RegulatorVoltCurrent']
            substationEquipmentInspection.RegulatorMaxAmp=Dict['RegulatorMaxAmp']
            substationEquipmentInspection.SurgeProtectorVisual=GetObjectFromidandReverseSortedIndex('SurgeProtectorVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilLeak=GetObjectFromidandReverseSortedIndex('TransformerOilLeak', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilLevel=GetObjectFromidandReverseSortedIndex('TransformerOilLevel', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerOilTemperatureCurrent=Dict['TransformerOilTemperatureCurrent']
            substationEquipmentInspection.TransformerOilTemperatureMaximum=Dict['TransformerOilTemperatureMaximum']
            substationEquipmentInspection.TransformerNitrogenPressure=Dict['TransformerNitrogenPressure']
            substationEquipmentInspection.TransformerOilVisual=GetObjectFromidandReverseSortedIndex('TransformerOilVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.TransformerWindingTemperatureCurrent=Dict['TransformerWindingTemperatureCurrent']
            substationEquipmentInspection.TransformerWindingTemperatureMaximum=Dict['TransformerWindingTemperatureMaximum']
            substationEquipmentInspection.SubstationEquipment=GetObjectFromidandReverseSortedIndex('SubstationEquipment', djangoproject.models.substationmodel.SubstationEquipment, Dict)
            substationEquipmentInspection.MechanismCharge=GetObjectFromidandReverseSortedIndex('MechanismCharge', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.FanWorkingVisual=GetObjectFromidandReverseSortedIndex('FanWorkingVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationEquipmentInspection.DemandAmpA=Dict['DemandAmpA']
            substationEquipmentInspection.DemandAmpB=Dict['DemandAmpB']
            substationEquipmentInspection.DemandAmpC=Dict['DemandAmpC']
            substationEquipmentInspection.OverCurrentTrip=Dict['OverCurrentTrip']
            substationEquipmentInspection.BreakerCounter=Dict['BreakerCounter']
            substationEquipmentInspection.save()
            ReturnObject=substationEquipmentInspection
        elif(self.Name=='DeleteSubstationEquipmentInspection'):
            substationEquipmentInspection=SubstationEquipmentInspection.objects.filter(id=Dict['Objectid'])[0]
            if(abs((substationEquipmentInspection.CreateDateTime - datetime.datetime.now()).days) > 30):
                ReturnObject='Substation Equipment Inspection Not Deleted, over 30 days old'
            else:
                substationEquipmentInspection.delete()
                ReturnObject='Deleted Substation Equipment Inpsection Object'
        elif(self.Name=='CreateSubstationEquipmentTemplate'):
            substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate()
            substationEquipmentTemplate.Name=Dict['ObjectName']
            substationEquipmentTemplate.DescriptionOrder=Dict['DescriptionOrder']
            substationEquipmentTemplate.BatteryTestOrder=Dict['BatteryTestOrder']
            substationEquipmentTemplate.BatteryVoltageNormalOrder=Dict['BatteryVoltageNormalOrder']
            substationEquipmentTemplate.BatteryVoltageTestOrder=Dict['BatteryVoltageTestOrder']
            substationEquipmentTemplate.BatteryChargeOrder=Dict['BatteryChargeOrder']
            substationEquipmentTemplate.BatteryVisualOrder=Dict['BatteryVisualOrder']
            substationEquipmentTemplate.GroundOrder=Dict['GroundOrder']
            substationEquipmentTemplate.VisualOrder=Dict['VisualOrder']
            substationEquipmentTemplate.GroundGridGateOrder=Dict['GroundGridGateOrder']
            substationEquipmentTemplate.GroundGridGoabSwitchOrder=Dict['GroundGridGoabSwitchOrder']
            substationEquipmentTemplate.GroundGridSwitchHandleOrder=Dict['GroundGridSwitchHandleOrder']
            substationEquipmentTemplate.GroundGridTowerOrder=Dict['GroundGridTowerOrder']
            substationEquipmentTemplate.GroundGridTransformerOrder=Dict['GroundGridTransformerOrder']
            substationEquipmentTemplate.MeterKWHOrder=Dict['MeterKWHOrder']
            substationEquipmentTemplate.MeterKWOrder=Dict['MeterKWOrder']
            substationEquipmentTemplate.RecloserAmperageAOrder=Dict['RecloserAmperageAOrder']
            substationEquipmentTemplate.RecloserAmperageBOrder=Dict['RecloserAmperageBOrder']
            substationEquipmentTemplate.RecloserAmperageCOrder=Dict['RecloserAmperageCOrder']
            substationEquipmentTemplate.RecloserAmperageGroundOrder=Dict['RecloserAmperageGroundOrder']
            substationEquipmentTemplate.RecloserMaxDemandAOrder=Dict['RecloserMaxDemandAOrder']
            substationEquipmentTemplate.RecloserMaxDemandBOrder=Dict['RecloserMaxDemandBOrder']
            substationEquipmentTemplate.RecloserMaxDemandCOrder=Dict['RecloserMaxDemandCOrder']
            substationEquipmentTemplate.RecloserMaxDemandGroundOrder=Dict['RecloserMaxDemandGroundOrder']
            substationEquipmentTemplate.RecloserOperationCounterOrder=Dict['RecloserOperationCounterOrder']
            substationEquipmentTemplate.RecloserOperationSummaryAOrder=Dict['RecloserOperationSummaryAOrder']
            substationEquipmentTemplate.RecloserOperationSummaryBOrder=Dict['RecloserOperationSummaryBOrder']
            substationEquipmentTemplate.RecloserOperationSummaryCOrder=Dict['RecloserOperationSummaryCOrder']
            substationEquipmentTemplate.RecloserTargetAOrder=Dict['RecloserTargetAOrder']
            substationEquipmentTemplate.RecloserTargetBOrder=Dict['RecloserTargetBOrder']
            substationEquipmentTemplate.RecloserTargetCOrder=Dict['RecloserTargetCOrder']
            substationEquipmentTemplate.RecloserTargetGroundOrder=Dict['RecloserTargetGroundOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionMinimumOrder=Dict['RegulatorDragHandPositionMinimumOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionCurrentOrder=Dict['RegulatorDragHandPositionCurrentOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionMaximumOrder=Dict['RegulatorDragHandPositionMaximumOrder']
            substationEquipmentTemplate.RegulatorVoltCurrentOrder=Dict['RegulatorVoltCurrentOrder']
            substationEquipmentTemplate.RegulatorVoltLowOrder=Dict['RegulatorVoltLowOrder']
            substationEquipmentTemplate.RegulatorVoltHighOrder=Dict['RegulatorVoltHighOrder']
            substationEquipmentTemplate.RegulatorMaxAmpOrder=Dict['RegulatorMaxAmpOrder']
            substationEquipmentTemplate.SurgeProtectorVisualOrder=Dict['SurgeProtectorVisualOrder']
            substationEquipmentTemplate.TransformerOilLeakOrder=Dict['TransformerOilLeakOrder']
            substationEquipmentTemplate.TransformerOilLevelOrder=Dict['TransformerOilLevelOrder']
            substationEquipmentTemplate.TransformerOilTemperatureCurrentOrder=Dict['TransformerOilTemperatureCurrentOrder']
            substationEquipmentTemplate.TransformerOilTemperatureMaximumOrder=Dict['TransformerOilTemperatureMaximumOrder']
            substationEquipmentTemplate.TransformerNitrogenPressureOrder=Dict['TransformerNitrogenPressureOrder']
            substationEquipmentTemplate.TransformerOilVisualOrder=Dict['TransformerOilVisualOrder']
            substationEquipmentTemplate.TransformerWindingTemperatureCurrentOrder=Dict['TransformerWindingTemperatureMaximumOrder']
            substationEquipmentTemplate.TransformerWindingTemperatureCurrentOrder=Dict['TransformerWindingTemperatureMaximumOrder']
            substationEquipmentTemplate.BatteryBankEquipmentIndicator=Dict['BatteryBankEquipmentIndicator']
            substationEquipmentTemplate.RegulatorEquipmentIndicator=Dict['RegulatorEquipmentIndicator']
            substationEquipmentTemplate.RecloserEquipmentIndicator=Dict['RecloserEquipmentIndicator']
            substationEquipmentTemplate.ActiveIndicator=Dict['ActiveIndicator']
            substationEquipmentTemplate.OperationCounterOrder=Dict['OperationCounterOrder']
            substationEquipmentTemplate.FanWorkingVisualOrder=Dict['FanWorkingVisualOrder']
            substationEquipmentTemplate.MechanismChargeOrder=Dict['MechanismChargeOrder']
            substationEquipmentTemplate.DemandAmpAOrder=Dict['DemandAmpAOrder']
            substationEquipmentTemplate.DemandAmpBOrder=Dict['DemandAmpBOrder']
            substationEquipmentTemplate.DemandAmpCOrder=Dict['DemandAmpCOrder']
            substationEquipmentTemplate.OverCurrentTripOrder=Dict['OverCurrentTripOrder']
            substationEquipmentTemplate.BreakerCounterOrder=Dict['BreakerCounterOrder']
            substationEquipmentTemplate.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentTemplate.save()
            ReturnObject=substationEquipmentTemplate
        elif(self.Name=='EditSubstationEquipmentTemplate'):
            substationEquipmentTemplate=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.substationmodel.SubstationEquipmentTemplate, Dict)
            substationEquipmentTemplate.Name=Dict['ObjectName']
            substationEquipmentTemplate.DescriptionOrder=Dict['DescriptionOrder']
            substationEquipmentTemplate.BatteryTestOrder=Dict['BatteryTestOrder']
            substationEquipmentTemplate.BatteryVoltageNormalOrder=Dict['BatteryVoltageNormalOrder']
            substationEquipmentTemplate.BatteryVoltageTestOrder=Dict['BatteryVoltageTestOrder']
            substationEquipmentTemplate.BatteryChargeOrder=Dict['BatteryChargeOrder']
            substationEquipmentTemplate.BatteryVisualOrder=Dict['BatteryVisualOrder']
            substationEquipmentTemplate.GroundOrder=Dict['GroundOrder']
            substationEquipmentTemplate.VisualOrder=Dict['VisualOrder']
            substationEquipmentTemplate.MeterKWHOrder=Dict['MeterKWHOrder']
            substationEquipmentTemplate.MeterKWOrder=Dict['MeterKWOrder']
            substationEquipmentTemplate.RecloserAmperageAOrder=Dict['RecloserAmperageAOrder']
            substationEquipmentTemplate.RecloserAmperageBOrder=Dict['RecloserAmperageBOrder']
            substationEquipmentTemplate.RecloserAmperageCOrder=Dict['RecloserAmperageCOrder']
            substationEquipmentTemplate.RecloserAmperageGroundOrder=Dict['RecloserAmperageGroundOrder']
            substationEquipmentTemplate.RecloserMaxDemandAOrder=Dict['RecloserMaxDemandAOrder']
            substationEquipmentTemplate.RecloserMaxDemandBOrder=Dict['RecloserMaxDemandBOrder']
            substationEquipmentTemplate.RecloserMaxDemandCOrder=Dict['RecloserMaxDemandCOrder']
            substationEquipmentTemplate.RecloserMaxDemandGroundOrder=Dict['RecloserMaxDemandGroundOrder']
            substationEquipmentTemplate.RecloserOperationCounterOrder=Dict['RecloserOperationCounterOrder']
            substationEquipmentTemplate.RecloserOperationSummaryAOrder=Dict['RecloserOperationSummaryAOrder']
            substationEquipmentTemplate.RecloserOperationSummaryBOrder=Dict['RecloserOperationSummaryBOrder']
            substationEquipmentTemplate.RecloserOperationSummaryCOrder=Dict['RecloserOperationSummaryCOrder']
            substationEquipmentTemplate.RecloserTargetAOrder=Dict['RecloserTargetAOrder']
            substationEquipmentTemplate.RecloserTargetBOrder=Dict['RecloserTargetBOrder']
            substationEquipmentTemplate.RecloserTargetCOrder=Dict['RecloserTargetCOrder']
            substationEquipmentTemplate.RecloserTargetGroundOrder=Dict['RecloserTargetGroundOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionMinimumOrder=Dict['RegulatorDragHandPositionMinimumOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionCurrentOrder=Dict['RegulatorDragHandPositionCurrentOrder']
            substationEquipmentTemplate.RegulatorDragHandPositionMaximumOrder=Dict['RegulatorDragHandPositionMaximumOrder']
            substationEquipmentTemplate.RegulatorVoltCurrentOrder=Dict['RegulatorVoltCurrentOrder']
            substationEquipmentTemplate.RegulatorVoltLowOrder=Dict['RegulatorVoltLowOrder']
            substationEquipmentTemplate.RegulatorVoltHighOrder=Dict['RegulatorVoltHighOrder']
            substationEquipmentTemplate.RegulatorMaxAmpOrder=Dict['RegulatorMaxAmpOrder']
            substationEquipmentTemplate.SurgeProtectorVisualOrder=Dict['SurgeProtectorVisualOrder']
            substationEquipmentTemplate.TransformerOilLeakOrder=Dict['TransformerOilLeakOrder']
            substationEquipmentTemplate.TransformerOilLevelOrder=Dict['TransformerOilLevelOrder']
            substationEquipmentTemplate.TransformerOilTemperatureCurrentOrder=Dict['TransformerOilTemperatureCurrentOrder']
            substationEquipmentTemplate.TransformerOilTemperatureMaximumOrder=Dict['TransformerOilTemperatureMaximumOrder']
            substationEquipmentTemplate.TransformerNitrogenPressureOrder=Dict['TransformerNitrogenPressureOrder']
            substationEquipmentTemplate.TransformerOilVisualOrder=Dict['TransformerOilVisualOrder']
            substationEquipmentTemplate.TransformerWindingTemperatureCurrentOrder=Dict['TransformerWindingTemperatureCurrentOrder']
            substationEquipmentTemplate.TransformerWindingTemperatureMaximumOrder=Dict['TransformerWindingTemperatureMaximumOrder']
            substationEquipmentTemplate.ActiveIndicator=Dict['ActiveIndicator']
            substationEquipmentTemplate.OperationCounterOrder=Dict['OperationCounterOrder']
            substationEquipmentTemplate.FanWorkingVisualOrder=Dict['FanWorkingVisualOrder']
            substationEquipmentTemplate.MechanismChargeOrder=Dict['MechanismChargeOrder']
            substationEquipmentTemplate.DemandAmpAOrder=Dict['DemandAmpAOrder']
            substationEquipmentTemplate.DemandAmpBOrder=Dict['DemandAmpBOrder']
            substationEquipmentTemplate.DemandAmpCOrder=Dict['DemandAmpCOrder']
            substationEquipmentTemplate.OverCurrentTripOrder=Dict['OverCurrentTripOrder']
            substationEquipmentTemplate.BreakerCounterOrder=Dict['BreakerCounterOrder']
            substationEquipmentTemplate.save()
            ReturnObject=substationEquipmentTemplate
        elif(self.Name=='DeleteSubstationEquipmentTemplate'):
            substationEquipmentTemplate=djangoproject.models.substationmodel.SubstationEquipmentTemplate.objects.filter(id=Dict['Objectid'])[0]
            if(not SubstationEquipment.objects.filter(SubstationEquipmentTemplate=substationEquipmentTemplate)):
                substationEquipmentTemplate.delete()
                ReturnObject='Deleted Substation Equipment Template'
            else:
                ReturnObject='Did Not Delete SubstationEquipmentTemplate, related SubstationEquipment exists.'
        elif(self.Name=='CreateSubstationInspection'):
            substationInspection=djangoproject.models.substationmodel.SubstationInspection()
            substationInspection.Substation=GetObjectFromidandReverseSortedIndex('Substation', djangoproject.models.substationmodel.Substation, Dict)
            substationInspection.Description=Dict['Description']
            substationInspection.CreateDateTime=Dict['CreateDateTime']
            substationInspection.CreateUserName=Dict['CreateUserName']
            substationInspection.LastModifyDateTime=Dict['CreateDateTime']
            substationInspection.LastModifyUserName=Dict['CreateUserName']
            substationInspection.DynasphereVisual=GetObjectFromidandReverseSortedIndex('DynasphereVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.BrokenPorcelain=GetObjectFromidandReverseSortedIndex('BrokenPorcelain', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.CircuitIdentifier=GetObjectFromidandReverseSortedIndex('CircuitIdentifier', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.DynasphereOperationIndicator=Dict['DynasphereOperationIndicator']
            substationInspection.SurgeProtectorVisual=GetObjectFromidandReverseSortedIndex('SurgeProtectorVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.Debris=GetObjectFromidandReverseSortedIndex('Debris', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceGroundLevel=GetObjectFromidandReverseSortedIndex('FenceGroundLevel', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceOverallCondition=GetObjectFromidandReverseSortedIndex('FenceOverallCondition', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceSecurityWire=GetObjectFromidandReverseSortedIndex('FenceSecurityWire', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceWarningSign=GetObjectFromidandReverseSortedIndex('FenceWarningSign', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateGround=GetObjectFromidandReverseSortedIndex('GateGround', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateLock=GetObjectFromidandReverseSortedIndex('GateLock', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateWarningSign=GetObjectFromidandReverseSortedIndex('GateWarningSign', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.MaterialStore=GetObjectFromidandReverseSortedIndex('MaterialStore', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.SpillPreventionPlan=GetObjectFromidandReverseSortedIndex('SpillPreventionPlan', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.AMRVisual=GetObjectFromidandReverseSortedIndex('AMRVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.Vegetation=GetObjectFromidandReverseSortedIndex('Vegetation', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationInspection.save()
            ReturnObject=substationInspection
        elif(self.Name=='EditSubstationInspection'):
            substationInspection=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.substationmodel.SubstationInspection, Dict)
            substationInspection.Substation=GetObjectFromidandReverseSortedIndex('Substation', djangoproject.models.substationmodel.Substation, Dict)
            substationInspection.Description=Dict['Description']
            substationInspection.LastModifyDateTime=Dict['LastModifyDateTime']
            substationInspection.LastModifyUserName=Dict['LastModifyUserName']
            substationInspection.DynasphereVisual=GetObjectFromidandReverseSortedIndex('DynasphereVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.BrokenPorcelain=GetObjectFromidandReverseSortedIndex('BrokenPorcelain', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.CircuitIdentifier=GetObjectFromidandReverseSortedIndex('CircuitIdentifier', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.DynasphereOperationIndicator=Dict['DynasphereOperationIndicator']
            substationInspection.SurgeProtectorVisual=GetObjectFromidandReverseSortedIndex('SurgeProtectorVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.Debris=GetObjectFromidandReverseSortedIndex('Debris', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceGroundLevel=GetObjectFromidandReverseSortedIndex('FenceGroundLevel', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceOverallCondition=GetObjectFromidandReverseSortedIndex('FenceOverallCondition', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceSecurityWire=GetObjectFromidandReverseSortedIndex('FenceSecurityWire', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.FenceWarningSign=GetObjectFromidandReverseSortedIndex('FenceWarningSign', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateGround=GetObjectFromidandReverseSortedIndex('GateGround', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateLock=GetObjectFromidandReverseSortedIndex('GateLock', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.GateWarningSign=GetObjectFromidandReverseSortedIndex('GateWarningSign', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.MaterialStore=GetObjectFromidandReverseSortedIndex('MaterialStore', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.SpillPreventionPlan=GetObjectFromidandReverseSortedIndex('SpillPreventionPlan', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.AMRVisual=GetObjectFromidandReverseSortedIndex('AMRVisual', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.Vegetation=GetObjectFromidandReverseSortedIndex('Vegetation', djangoproject.models.substationmodel.SubstationInspectionChoice, Dict)
            substationInspection.save()
            ReturnObject=substationInspection
        elif(self.Name=='DeleteSubstationInspection'):
            substationInspection=SubstationInspection.objects.filter(id=Dict['Objectid'])[0]
            if(abs((substationInspection.CreateDateTime - datetime.datetime.now()).days) > 30):
                ReturnObject='Substation Inspection Not Deleted, over 30 days old'
            else:
                substationEquipmentInspection.delete()
                ReturnObject='Deleted Equipment Inpsection Object'
        elif(self.Name=='CreateSubstationInspectionChoice'):
            substationInspectionChoice=djangoproject.models.substationmodel.SubstationInspectionChoice()
            substationInspectionChoice.Name=Dict['ObjectName']
            substationInspectionChoice.Description=Dict['Description']
            substationInspectionChoice.ActiveIndicator=Dict['ActiveIndicator']
            substationInspectionChoice.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationInspectionChoice.save()
            ReturnObject=substationInspectionChoice
        elif(self.Name=='EditSubstationInspectionChoice'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substationInspectionChoice=djangoproject.models.substationmodel.SubstationInspectionChoice.objects.filter(id=Dict['Objectid'])[0]
            else:
                substationInspectionChoice=djangoproject.models.substationmodel.SubstationInspectionChoice.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            substationInspectionChoice.Name=Dict['ObjectName']
            substationInspectionChoice.Description=Dict['Description']
            substationInspectionChoice.ActiveIndicator=Dict['ActiveIndicator']
            substationInspectionChoice.save()
            ReturnObject=substationInspectionChoice
        elif(self.Name=='CreateSubstationEquipmentModelType'):
            substationEquipmentModelType=djangoproject.models.substationmodel.SubstationEquipmentModelType()
            if(Dict['Manufacturerid'] and Dict['Manufacturerid'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['Manufacturerid'])[0]
            elif(Dict['ManufacturerIndexWhenReverseSorted'] <> None and Dict['ManufacturerIndexWhenReverseSorted'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['ManufacturerIndexWhenReverseSorted']]
            else:
                manufacturer=None
            substationEquipmentModelType.Manufacturer=manufacturer
            substationEquipmentModelType.Name=Dict['ObjectName']
            substationEquipmentModelType.Description=Dict['Description']
            substationEquipmentModelType.TransformerIndicator=Dict['TransformerIndicator']
            substationEquipmentModelType.RegulatorIndicator=Dict['RegulatorIndicator']
            substationEquipmentModelType.RegulatorControllerIndicator=Dict['RegulatorControllerIndicator']
            substationEquipmentModelType.TransmissionOverCurrentRelayIndicator=Dict['TransmissionOverCurrentRelayIndicator']
            substationEquipmentModelType.RecloserIndicator=Dict['RecloserIndicator']
            substationEquipmentModelType.RecloserControllerIndicator=Dict['RecloserControllerIndicator']
            substationEquipmentModelType.CircuitSwitcherIndicator=Dict['CircuitSwitcherIndicator']
            substationEquipmentModelType.BatteryBankIndicator=Dict['BatteryBankIndicator']
            substationEquipmentModelType.save()
            ReturnObject=substationEquipmentModelType
        elif(self.Name=='EditSubstationEquipmentModelType'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substationEquipmentModelType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.filter(id=Dict['Objectid'])[0]
            elif(Dict['ObjectIndexWhenReverseSorted'] <> None and Dict['ObjectIndexWhenReverseSorted'] <> -1):
                substationEquipmentModelType=djangoproject.models.substationmodel.SubstationEquipmentModelType.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            if(Dict['Manufacturerid'] and Dict['Manufacturerid'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.filter(id=Dict['Manufacturerid'])[0]
            elif(Dict['ManufacturerIndexWhenReverseSorted'] <> None and Dict['ManufacturerIndexWhenReverseSorted'] <> -1):
                manufacturer=djangoproject.models.compatibleunit.Company.objects.all().order_by('-id')[Dict['ManufacturerIndexWhenReverseSorted']]
            else:
                manufacturer=None
            substationEquipmentModelType.Manufacturer=manufacturer
            substationEquipmentModelType.Name=Dict['ObjectName']
            substationEquipmentModelType.Description=Dict['Description']
            substationEquipmentModelType.TransformerIndicator=Dict['TransformerIndicator']
            substationEquipmentModelType.RegulatorIndicator=Dict['RegulatorIndicator']
            substationEquipmentModelType.RegulatorControllerIndicator=Dict['RegulatorControllerIndicator']
            substationEquipmentModelType.TransmissionOverCurrentRelayIndicator=Dict['TransmissionOverCurrentRelayIndicator']
            substationEquipmentModelType.RecloserIndicator=Dict['RecloserIndicator']
            substationEquipmentModelType.RecloserControllerIndicator=Dict['RecloserControllerIndicator']
            substationEquipmentModelType.CircuitSwitcherIndicator=Dict['CircuitSwitcherIndicator']
            substationEquipmentModelType.BatteryBankIndicator=Dict['BatteryBankIndicator']
            substationEquipmentModelType.save()
            ReturnObject=substationEquipmentModelType
        elif(self.Name=='CreateSubstationEquipmentSetting'):
            substationEquipmentSetting=djangoproject.models.substationmodel.SubstationEquipmentSetting()
            substationEquipmentSetting.Name=Dict['ObjectName']
            substationEquipmentSetting.Description=Dict['Description']
            substationEquipmentSetting.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentSetting.save()
            ReturnObject=substationEquipmentSetting
        elif(self.Name=='EditSubstationEquipmentSetting'):
            substationEquipmentSetting=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.substationmodel.SubstationEquipmentSetting, Dict)
            substationEquipmentSetting.Description=Dict['Description']
            substationEquipmentSetting.Name=Dict['ObjectName']
            substationEquipmentSetting.save()
            ReturnObject=substationEquipmentSetting
        elif(self.Name=='DeleteSubstationEquipmentSetting'):
            substationEquipmentSetting=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.substationmodel.SubstationEquipmentSetting, Dict)
            substationEquipmentSetting.delete()
        elif(self.Name=='CreateSubstationEquipmentSettingAssignment'):
            substationEquipmentSettingAssignment=djangoproject.models.substationmodel.SubstationEquipmentSettingAssignment()
            substationEquipmentSettingAssignment.SubstationEquipmentSetting=GetObjectFromidandReverseSortedIndex('SubstationEquipmentSetting', djangoproject.models.substationmodel.SubstationEquipmentSetting, Dict)
            substationEquipmentSettingAssignment.SubstationEquipment=GetObjectFromidandReverseSortedIndex('SubstationEquipment', djangoproject.models.substationmodel.SubstationEquipment, Dict)
            substationEquipmentSettingAssignment.DateTime=Dict['DateTime']
            substationEquipmentSettingAssignment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentSettingAssignment.save()
            ReturnObject=substationEquipmentSettingAssignment
        elif(self.Name=='CreateSubstationEquipmentSubstationAssignment'):
            substationEquipmentSubstationAssignment=djangoproject.models.substationmodel.SubstationEquipmentSubstationAssignment()
            substation=GetObjectFromidandReverseSortedIndex('Substation', djangoproject.models.substationmodel.Substation, Dict)
            substationEquipment=GetObjectFromidandReverseSortedIndex('SubstationEquipment', djangoproject.models.substationmodel.SubstationEquipment, Dict)
            substationEquipmentSubstationAssignment.Substation=substation
            substationEquipmentSubstationAssignment.SubstationEquipment=substationEquipment
            substationEquipmentSubstationAssignment.Description=Dict['Description']
            substationEquipmentSubstationAssignment.DateTime=Dict['DateTime']
            substationEquipmentSubstationAssignment.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentSubstationAssignment.save()
            substationEquipment.SetCurrentSubstation()
            ReturnObject=substationEquipmentSubstationAssignment
        elif(self.Name=='CreateSubstationEquipmentCircuitAssignment'):
            substationEquipmentCircuitAssignment=djangoproject.models.substationmodel.SubstationEquipmentCircuitAssignment()
            substationEquipment=GetObjectFromidandReverseSortedIndex('SubstationEquipment', djangoproject.models.substationmodel.SubstationEquipment, Dict)
            substationCircuit=GetObjectFromidandReverseSortedIndex('SubstationCircuit', djangoproject.models.substationmodel.SubstationCircuit, Dict)
            substationEquipmentCircuitAssignment.SubstationCircuit=substationCircuit
            substationEquipmentCircuitAssignment.SubstationEquipment=substationEquipment
            substationEquipmentCircuitAssignment.Description=Dict['Description']
            substationEquipmentCircuitAssignment.DateTime=Dict['DateTime']
            substationEquipmentCircuitAssignment.save()
            ReturnObject=substationEquipmentCircuitAssignment
        elif(self.Name=='CreateSubstationCircuit'):
            substationCircuit=djangoproject.models.substationmodel.SubstationCircuit()
            substationCircuit.Name=Dict['ObjectName']
            substationCircuit.Description=Dict['Description']
            substationCircuit.CircuitNumber=Dict['CircuitNumber']
            substation=GetObjectFromidandReverseSortedIndex('Substation', djangoproject.models.substationmodel.Substation, Dict)
            substationCircuit.Substation=substation
            substationCircuit.AMRCircuitName=Dict['AMRCircuitName']
            substationCircuit.AMRSubstationIdentifier=Dict['AMRSubstationIdentifier']
            substationCircuit.AMRBusIdentifier=Dict['AMRBusIdentifier']
            substationCircuit.AMRFeederIdentifier=Dict['AMRFeederIdentifier']
            substationCircuit.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationCircuit.save()
            ReturnObject=substationCircuit
        elif(self.Name=='EditSubstationCircuit'):
            substationCircuit=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.substationmodel.SubstationCircuit, Dict)
            substationCircuit.Name=Dict['ObjectName']
            substationCircuit.CircuitNumber=Dict['CircuitNumber']
            substationCircuit.Description=Dict['Description']
            substation=GetObjectFromidandReverseSortedIndex('Substation', djangoproject.models.substationmodel.Substation, Dict)
            substationCircuit.Substation=substation
            substationCircuit.AMRCircuitName=Dict['AMRCircuitName']
            substationCircuit.AMRSubstationIdentifier=Dict['AMRSubstationIdentifier']
            substationCircuit.AMRBusIdentifier=Dict['AMRBusIdentifier']
            substationCircuit.AMRFeederIdentifier=Dict['AMRFeederIdentifier']
            substationCircuit.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationCircuit.save()
            ReturnObject=substationCircuit
        elif(self.Name=='CreateSubstationEquipmentTest'):
            substationEquipmentTest=djangoproject.models.substationmodel.SubstationEquipmentTest()
            if(Dict['SubstationEquipmentid'] and Dict['SubstationEquipmentid'] <> -1):
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.filter(id=Dict['SubstationEquipmentid'])[0]
            else:
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.all().order_by('-id')[Dict['SubstationEquipmentIndexWhenReverseSorted']]
            substationEquipmentTest.SubstationEquipment=substationEquipment
            substationEquipmentTest.PassIndicator=Dict['PassIndicator']
            substationEquipmentTest.Description=Dict['Description']
            substationEquipmentTest.DateTime=Dict['DateTime']
            if(not substationEquipmentTest.DateTime):#FIXME not sure why this is needed, Dict has a Date Type already instead of a string
                substationEquipmentTest.DateTime=Dict['DateTime']
            substationEquipmentTest.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            substationEquipmentTest.save()
            ReturnObject=substationEquipmentTest
        elif(self.Name=='EditSubstationEquipmentTest'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                substationEquipmentTest=djangoproject.models.substationmodel.SubstationEquipmentTest.objects.filter(id=Dict['ObjectEquipmentid'])[0]
            else:
                substationEquipmentTest=djangoproject.models.substationmodel.SubstationEquipmentTest.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            if(Dict['SubstationEquipmentid'] and Dict['SubstationEquipmentid'] <> -1):
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.filter(id=Dict['SubstationEquipmentid'])[0]
            else:
                substationEquipment=djangoproject.models.substationmodel.SubstationEquipment.objects.all().order_by('-id')[Dict['SubstationEquipmentIndexWhenReverseSorted']]
            substationEquipmentTest.SubstationEquipment=substationEquipment
            substationEquipmentTest.PassIndicator=Dict['PassIndicator']
            substationEquipmentTest.Description=Dict['Description']
            substationEquipmentTest.DateTime=Dict['DateTime']
            if(not substationEquipmentTest.DateTime):  #FIXME not sure why this is needed, Dict has a Date Type already instead of a string
                substationEquipmentTest.DateTime=Dict['DateTime']
            substationEquipmentTest.save()
            ReturnObject=substationEquipmentTest
        elif(self.Name=='DeleteSubstationEquipmentTest'):
            substationEquipmentTest=djangoproject.models.substationmodel.SubstationEquipmentTest.objects.filter(id=Dict['Objectid'])[0]
            substationEquipmentTest.delete()
        elif(self.Name=='CreateVoltage'):
            voltage=djangoproject.models.compatibleunit.Voltage()
            voltage.Name=Dict['ObjectName']
            voltage.Description=Dict['Description']
            voltage.Value=Dict['Value']
            voltage.TransmissionIndicator=Dict['TransmissionIndicator']
            voltage.PrimaryIndicator=Dict['PrimaryIndicator']
            voltage.SecondaryIndicator=Dict['SecondaryIndicator']
            voltage.ServiceIndicator=Dict['ServiceIndicator']
            voltage.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            voltage.save()
            ReturnObject=voltage
        elif(self.Name=='EditVoltage'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                voltage=djangoproject.models.compatibleunit.Voltage.objects.filter(id=Dict['Objectid'])[0]
            else:
                voltage=djangoproject.models.compatibleunit.Voltage.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            voltage.Name=Dict['ObjectName']
            voltage.Description=Dict['Description']
            voltage.Value=Dict['Value']
            voltage.TransmissionIndicator=Dict['TransmissionIndicator']
            voltage.PrimaryIndicator=Dict['PrimaryIndicator']
            voltage.SecondaryIndicator=Dict['SecondaryIndicator']
            voltage.ServiceIndicator=Dict['ServiceIndicator']
            voltage.save()
            ReturnObject=voltage
        elif(self.Name=='CreateWarehouseMeterInventoryCheckIn'):
            warehouseMeterInventoryCheckIn=djangoproject.models.compatibleunit.WarehouseMeterInventoryCheckIn()
            warehouseMeterInventoryCheckIn.WarehouseMeterInspectionChoice=GetObjectFromidandReverseSortedIndex('WarehouseMeterInspectionChoice', djangoproject.models.compatibleunit.WarehouseMeterInspectionChoice, Dict)
            warehouseMeterInventoryCheckIn.MeterDCSINumber=Dict['MeterDCSINumber']
            warehouseMeterInventoryCheckIn.MeterNumber=Dict['MeterNumber']
            if(Dict['CheckInDateTime']):
                warehouseMeterInventoryCheckIn.CheckInDateTime=Dict['CheckInDateTime']
            else:
                warehouseMeterInventoryCheckIn.CheckInDateTime=None
            if(Dict['CheckOutDateTime']):
                warehouseMeterInventoryCheckIn.CheckOutDateTime=Dict['CheckOutDateTime']
            else:
                warehouseMeterInventoryCheckIn.CheckOutDateTime=None
            if(Dict['InspectionDateTime']):
                warehouseMeterInventoryCheckIn.InspectionDateTime=Dict['InspectionDateTime']
            else:
                warehouseMeterInventoryCheckIn.InspectionDateTime=None

            warehouseMeterInventoryCheckIn.Description=Dict['Description']
            warehouseMeterInventoryCheckIn.JunkIndicator=Dict['JunkIndicator']
            if(Dict['JunkDateTime']):
                warehouseMeterInventoryCheckIn.JunkDateTime=Dict['JunkDateTime']
            else:
                warehouseMeterInventoryCheckIn.JunkDateTime=None
            warehouseMeterInventoryCheckIn.Location=Dict['Location']
            warehouseMeterInventoryCheckIn.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            warehouseMeterInventoryCheckIn.save()
            ReturnObject=warehouseMeterInventoryCheckIn
        elif(self.Name=='EditWarehouseMeterInventoryCheckIn'):
            warehouseMeterInventoryCheckIn=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.compatibleunit.WarehouseMeterInventoryCheckIn, Dict)
            warehouseMeterInventoryCheckIn.WarehouseMeterInspectionChoice=GetObjectFromidandReverseSortedIndex('WarehouseMeterInspectionChoice', djangoproject.models.compatibleunit.WarehouseMeterInspectionChoice, Dict)
            warehouseMeterInventoryCheckIn.MeterDCSINumber=Dict['MeterDCSINumber']
            warehouseMeterInventoryCheckIn.MeterNumber=Dict['MeterNumber']
            if(Dict['CheckInDateTime']):
                warehouseMeterInventoryCheckIn.CheckInDateTime=Dict['CheckInDateTime']
            else:
                warehouseMeterInventoryCheckIn.CheckInDateTime=None
            if(Dict['CheckOutDateTime']):
                warehouseMeterInventoryCheckIn.CheckOutDateTime=Dict['CheckOutDateTime']
            else:
                warehouseMeterInventoryCheckIn.CheckOutDateTime=None
            if(Dict['InspectionDateTime']):
                warehouseMeterInventoryCheckIn.InspectionDateTime=Dict['InspectionDateTime']
            else:
                warehouseMeterInventoryCheckIn.InspectionDateTime=None

            warehouseMeterInventoryCheckIn.Description=Dict['Description']
            warehouseMeterInventoryCheckIn.JunkIndicator=Dict['JunkIndicator']
            if(Dict['JunkDateTime']):
                warehouseMeterInventoryCheckIn.JunkDateTime=Dict['JunkDateTime']
            else:
                warehouseMeterInventoryCheckIn.JunkDateTime=None
            warehouseMeterInventoryCheckIn.Location=Dict['Location']
            warehouseMeterInventoryCheckIn.save()
            ReturnObject=warehouseMeterInventoryCheckIn
        elif(self.Name=='CreateWarehouseMeterInspectionChoice'):
            warehouseMeterInspectionChoice=djangoproject.models.compatibleunit.WarehouseMeterInspectionChoice()
            warehouseMeterInspectionChoice.Name=Dict['ObjectName']
            warehouseMeterInspectionChoice.Description=Dict['Description']
            warehouseMeterInspectionChoice.ActiveIndicator=Dict['ActiveIndicator']
            warehouseMeterInspectionChoice.ResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
            warehouseMeterInspectionChoice.save()
            ReturnObject=warehouseMeterInspectionChoice
        elif(self.Name=='EditWarehouseMeterInspectionChoice'):
            if(Dict['Objectid'] and Dict['Objectid'] <> -1):
                warehouseMeterInspectionChoice=djangoproject.models.compatibleunit.WarehouseMeterInspectionChoice.objects.filter(id=Dict['Objectid'])[0]
            else:
                warehouseMeterInspectionChoice=djangoproject.models.compatibleunit.WarehouseMeterInspectionChoice.objects.all().order_by('-id')[Dict['ObjectIndexWhenReverseSorted']]
            warehouseMeterInspectionChoice.Name=Dict['ObjectName']
            warehouseMeterInspectionChoice.Description=Dict['Description']
            warehouseMeterInspectionChoice.ActiveIndicator=Dict['ActiveIndicator']
            warehouseMeterInspectionChoice.save()
            ReturnObject=warehouseMeterInspectionChoice
        elif(self.Name=='CreateGroundRodTest'):
            groundRodTest=compatibleunit.GroundRodTest()
            groundRodTest.StationIdentifier=geography.Station().GetOrCreateClosestStation(self.StartPoint).id
            groundRodTest.Point=self.StartPoint
            groundRodTest.GroundRodNumber= Dict['GroundRodNumber']
            groundRodTest.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            groundRodTest.WorkOrderNumber=Dict['WorkOrderNumber']
            groundRodTest.Description=Dict['Description']
            groundRodTest.SetupIndicator=Dict['SetupIndicator']
            groundRodTest.InspectionPersonName=Dict['InspectionPersonName']
            groundRodTest.SubstationName=Dict['SubstationName']
            groundRodTest.ResistanceReading=Dict['ResistanceReading']
            groundRodTest.GroundRodTestDate=Dict['GroundRodTestDate']
            groundRodTest.ResidesOnServerIndicator = djangoproject.settings.COOPGISServerIndicator
            groundRodTest.CreateDateTime=self.CommandCreateDateTime
            groundRodTest.LastModifyDateTime=self.CommandCreateDateTime
            groundRodTest.CreateUserName=self.CommandUserName
            groundRodTest.LastModifyUserName=self.CommandUserName
            groundRodTest.CreateCommand=self
            groundRodTest.save()
            geography.Station().GetOrCreateClosestStation(self.StartPoint).RebuildSymbology()
            ReturnObject=groundRodTest
        elif(self.Name=='EditGroundRodTest'):
            groundRodTest=compatibleunit.GroundRodTest.objects.filter(id=Dict['Objectid'])[0]
            groundRodTest.GroundRodNumber= Dict['GroundRodNumber']
            groundRodTest.Company=compatibleunit.Company.objects.filter(Name=Dict['CompanyName'])[0]
            groundRodTest.WorkOrderNumber=Dict['WorkOrderNumber']
            groundRodTest.Description=Dict['Description']
            groundRodTest.SetupIndicator=Dict['SetupIndicator']
            groundRodTest.InspectionPersonName=Dict['InspectionPersonName']
            groundRodTest.SubstationName=Dict['SubstationName']
            groundRodTest.ResistanceReading=Dict['ResistanceReading']
            groundRodTest.GroundRodTestDate=Dict['GroundRodTestDate']
            groundRodTest.ResidesOnServerIndicator = djangoproject.settings.COOPGISServerIndicator
            groundRodTest.LastModifyDateTime=self.CommandCreateDateTime
            groundRodTest.LastModifyUserName=self.CommandUserName
            groundRodTest.CreateCommand=self
            groundRodTest.save()
            geography.Station().GetOrCreateClosestStation(groundRodTest.Point).RebuildSymbology()
            ReturnObject=groundRodTest
        elif(self.Name=='DeleteGroundRodTest'):
            groundRodTest=compatibleunit.GroundRodTest.objects.filter(id__exact=Dict['GroundRodTestid'])[0]
            StartStation=geography.Station().GetOrCreateClosestStation(groundRodTest.Point)
            groundRodTest.delete()
            StartStation.RebuildSymbology()
            ReturnObject='Deleted'
        elif(self.Name=='CreateTransformerBank'):
            transformerBank=compatibleunit.TransformerBank()
            Station=GetObjectFromidandReverseSortedIndex('Station', djangoproject.models.geography.Station, Dict)
            transformerBank.Description=Dict['Description']
            transformerBank.TransformerBankType=djangoproject.models.compatibleunit.TransformerBankType.objects.filter(Name=Dict['TransformerBankTypeName'])[0]
            transformerBank.Station=Station
            transformerBank.ResidesOnServerIndicator = djangoproject.settings.COOPGISServerIndicator
            transformerBank.CreateCommand=self
            transformerBank.save()
            ReturnObject=transformerBank
        elif(self.Name=='DeleteTransformerBank'):
            transformerBank=GetObjectFromidandReverseSortedIndex('Object', djangoproject.models.compatibleunit.TransformerBank, Dict)
            Assemblies=djangoproject.models.compatibleunit.Assembly.objects.filter(TransformerBank=transformerBank)
            for i in Assemblies:
                i.TransformerBank=None
                i.save()
            transformerBank.delete()
            ReturnObject='Deleted'
        else:
            raise Exception('Aborted processing a Command, invalid command:  ' + self.Name)
        self.SetProcessedIndicators()
        return ReturnObject
    #************************END OF PROCESS *******************************************
    def Create(self, BypassDictionary=None, **SetDictionary):
        if(BypassDictionary):
            SetDictionary=BypassDictionary
        New=Command()
        New.Name=SetDictionary['Name']
        New.SetHardCodedFields(SetDictionary)
        New.CommandProcessedIndicator=False
        New.CommandResidesOnServerIndicator=djangoproject.settings.COOPGISServerIndicator
        New.CommandVerifiedIndicator=djangoproject.settings.COOPGISServerIndicator
        New.CommandProcessedDateTime=None
        try:
            New.CommandCreateDateTime=SetDictionary['CommandCreateDateTime']
        except KeyError:
            New.CommandCreateDateTime=datetime.datetime.now()
        New.CommandProcessFailedIndicator=False

        New.Dictionary=cPickle.dumps(SetDictionary)
        New.save()
        return New
    def GetDictionary(self):
        """Returns a Dictionary that contains Dictionary data"""
        Dict = cPickle.loads(str(self.Dictionary))
        return Dict
    def SetProcessedIndicators(self):
        self.CommandProcessedDateTime=datetime.datetime.now()
        self.CommandProcessedIndicator=True
        self.CommandProcessFailedIndicator=False
        self.save()
    def SetHardCodedFields(self, Dict):
        HardCodedFields=['Name', 'AssemblyName', 'TagNumber', 'StartPoint', 'EndPoint', 'Polygon', 'Line', 'CommandResidesOnServerIndicator', 
                                'CommandProcessedDateTime', 'CommandUserName', 'CommandCreateDateTime', 'CommandProcessFailedIndicator', 
                                'CommandVerifiedIndicator', 'CommandUpdateNumber']
        for i in HardCodedFields:
            if(Dict.has_key(i)):
                exec("self." + str(i) + "=Dict['" + str(i) + "']")


    def ImportDictionary(self, Dict, CommandUpdateNumber=''):  
        """ImportDict Imports a Dictionary Row to a Command Object"""
        New=Command()
        Dict['CommandVerifiedIndicator'] = False #On Import, Always False until set to True by a later function
        Dict['CommandUpdateNumber']=CommandUpdateNumber
        New=New.Create(BypassDictionary=Dict)
        return New
    def ExportToTextFile(self, TextFileName=None):
        """Exports all current commands to a Text file so they can be imported into a different DB"""
        if(not TextFileName):
            TextFileName=self.ExportToTextFileName
        commands=Command.objects.all().exclude(CommandResidesOnServerIndicator=True).order_by('Order')
        Rows=[]
        for i in commands:
            Rows.append(i.Dictionary)    
        TextFile=open(TextFileName, "w")
        TextFile.write(cPickle.dumps(Rows))
        TextFile.close()
    def ImportFromTextFile(self, TextFileName=None, UpdateNumber='Manual Import', ProcessIndicator=False, VerifyIndicator=True):
        """Imports a Text file of commands into the DB"""
        if(not TextFileName):
            TextFileName=self.ImportFromTextFileName
        TextFile=open(TextFileName, "r")
        TextFileString=TextFile.read()
        try:
            CommandDictionaries=cPickle.loads(str(TextFileString))
        except:
            CommandDictionaries=[]
        TextFile.close()

        for i in CommandDictionaries:
            self.ImportDictionary(i, UpdateNumber)
        CommandsImported=Command.objects.filter(CommandUpdateNumber=UpdateNumber).exclude(CommandProcessedIndicator=True)
        if(ProcessIndicator):
            for i in CommandsImported:
                try:
                    i.CommandVerifiedIndicator=True
                    i.save()
                    i.Process()
                except:
                    i.CommandProcessFailedIndicator=True
                    i.save()
        elif(VerifyIndicator):
            for i in CommandsImported:
                i.CommandVerifiedIndicator=True
                i.save()
    def Set(self, FieldName, Value):
        if not FieldName in CommandDictionary[self.Name] and not FieldName in CommandCommonFields:
            raise(Exception('Field Name invalid for Command Name:  ' + str(self.Name) + '   ' + str(FieldName)))
        Dict = self.GetDictionary()
        Dict[FieldName]=Value
        self.Dictionary=cPickle.dumps(Dict)
        self.SetHardCodedFields({FieldName: Value})
    def GetTextString(self):
        return self.Dictionary
    def __unicode__(self):
        return str(self.id) + ':  ' + self.Name


def DeleteAssembly(Assemblyid, UserName):
    """Returns the id of the command deleted if deleting a command was necessary, otherwise returns 0 if successful"""
    AssemblyToDelete=compatibleunit.Assembly.objects.filter(id=Assemblyid)[0]
    if(AssemblyToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeleteAssembly', Assemblyid=Assemblyid, CommandUserName=UserName)
        command=command.Process()
        return 0
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        commandid=int(str(AssemblyToDelete.CreateCommand.id))
        if(AssemblyToDelete.Station):
            StationOrSpan=AssemblyToDelete.Station
        else:
            StationOrSpan=AssemblyToDelete.Span
        AssemblyToDelete.delete()
        command=Command.objects.filter(id__exact=commandid)
        id=command[0].id
        command[0].delete()
        StationOrSpan.RebuildSymbology()
        return id

